Question

Is there a way to accessName inside the style? It is a property of objects in the list Foo

<DataGrid ItemsSource="{Binding Source=Foo}">
    ...
    <DataGridTextColumn Binding="{Binding Path=Name}">           // Works
        <DataGridTextColumn.EditingElementStyle>
            <Style TargetType="TextBox">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Path=Name}"   // Not Found

    ...
</DataGrid>

I cannot figure out how to reference Name from within the DataTrigger. I assume I am missing some sort of Source property in the binding.

Was it helpful?

Solution

The following code seems to work:

MainWindow.xaml

<Window x:Class="WpfScratchBox.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <DataGrid ItemsSource="{Binding Foo}" AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Name Column" Binding="{Binding Path=Name}">
                <DataGridTextColumn.EditingElementStyle>
                    <Style TargetType="TextBox">
                        <Style.Triggers>
                            <DataTrigger Binding="{Binding Path=Name}"  Value="Test">
                                <Setter Property="Background" Value="Red" />
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                </DataGridTextColumn.EditingElementStyle>
            </DataGridTextColumn>
        </DataGrid.Columns>
    </DataGrid>
</Grid>

MainWindow.xaml.cs

using System;
using System.Collections.ObjectModel;
using System.Windows;

namespace WpfScratchBox
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            Data d = new Data();
            Person a = new Person() { Name = "Person1" };
            Person b = new Person() { Name = "Person2" };
            Person c = new Person() { Name = "Test" };
            d.Foo.Add(a);
            d.Foo.Add(b);
            d.Foo.Add(c);
            this.DataContext = d;
        }
    }

    public class Data
    {
        public Data()
        {
            Foo = new ObservableCollection<Person>();
        }

        public ObservableCollection<Person> Foo { get; set; }
    }

    public class Person
    {
        public String Name { get; set; }
    }
}

And here's what it looks like.

Example application

If this doesn't work for you, then you need to give us more information about your datacontext type etc.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top