在样式之外获取DataContext

时间:2013-06-17 19:51:37

标签: wpf binding datagrid datatrigger

有没有办法在样式中访问Name?它是列表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>

我无法弄清楚如何在Name中引用DataTrigger。我假设我在绑定中缺少某种Source属性。

1 个答案:

答案 0 :(得分:2)

以下代码似乎有效:

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; }
    }
}

这就是它的样子。

Example application

如果这对您不起作用,那么您需要向我们提供有关您的datacontext类型等的更多信息。