XamDataGrid - 如何从 C# 代码创建 DataRecordPresenterStyle DataTrigger

XamDataGrid - How to create a DataRecordPresenterStyle DataTrigger from C# code

我正在尝试这样做:

<Style TargetType="{x:Type igDP:DataRecordPresenter}">
    <Style.Triggers>
        <DataTrigger Binding="{Binding DataItem.IsOnChart}" Value="true">
            <Setter Property="Opacity" Value="1"/>
        </DataTrigger>
        <DataTrigger Binding="{Binding DataItem.IsOnChart}" Value="false">
            <Setter Property="Opacity" Value="0.5"/>
        </DataTrigger>
    </Style.Triggers>
</Style>

来自 C#:

Style _DataRecordPresenterStyle = new Style(typeof(DataRecordPresenter));
_DataRecordPresenterStyle.Setters.Add(new Setter(DataRecordPresenter.OpacityProperty, 1));

var _DataTrigger = new DataTrigger() { Binding = new Binding("DataItem.IsOnChart"), Value = true };
_DataTrigger.Setters.Add(new Setter(DataRecordPresenter.OpacityProperty, 1));
_DataRecordPresenterStyle.Triggers.Add(_DataTrigger);

_DataTrigger = new DataTrigger() { Binding = new Binding("DataItem.IsOnChart"), Value = false };
_DataTrigger.Setters.Add(new Setter(DataRecordPresenter.OpacityProperty, 0.5));
_DataRecordPresenterStyle.Triggers.Add(_DataTrigger);

_Grid.FieldLayoutSettings.DataRecordPresenterStyle = _DataRecordPresenterStyle;

但是当我将数据绑定到网格时出现错误:

默认未处理异常:调用目标抛出异常。

数据确实有字段,它的类型是 bool,所有记录上的值为 true。

我做错了什么?

感谢您的宝贵时间。

"Exception has been thrown by the target of an invocation"就不多说了。您应该查看 InnerException 的消息。如果您在 XAML 标记中使用它,我还假设您已经验证 Style 本身有效。

以编程方式创建 Style 的推荐方法是使用 XamlReader class 并解析 XAML。试试这个:

string xaml = "<Style xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\" " +
    "xmlns:igDP=\"clr-namespace:Infragistics.Windows.DataPresenter;assembly=InfragisticsWPF4.DataPresenter.v12.1\" " +
    "TargetType=\"{x:Type igDP:DataRecordPresenter}\">" +
"<Style.Triggers>" +
        "<DataTrigger Binding=\"{Binding DataItem.IsOnChart}\" Value=\"true\">" +
            "<Setter Property=\"Opacity\" Value=\"1\"/>" +
        "</DataTrigger>" +
        "<DataTrigger Binding=\"{Binding DataItem.IsOnChart}\" Value=\"false\">" +
            "<Setter Property=\"Opacity\" Value=\"0.5\"/>" +
        "</DataTrigger>" +
    "</Style.Triggers>" +
"</Style>";

Style style = System.Windows.Markup.XamlReader.Parse(xaml) as Style;
style.Seal();

您可能需要将 "InfragisticsWPF4.DataPresenter.v12.1" 更改为定义了 DataRecordPresenter class 的程序集的实际名称。