【问题标题】:How to create a DataTrigger programatically with Binding="{Binding}"?如何使用 Binding="{Binding}" 以编程方式创建 DataTrigger?
【发布时间】:2021-11-06 08:59:28
【问题描述】:

这个DataTrigger 在 C# 代码中的等价物是什么?

<DataTrigger
  Binding="{Binding}"
  Value="{x:Null}">
    <Setter
      Property=SomeProperty
      Value=SomeValue />
</DataTrigger>

我对如何创建Binding 持怀疑态度。这是正确的吗?

var trigger = new DataTrigger();
trigger.Value = null;
// Is this sufficient?
trigger.Binding = new Binding();
// Code to create the setter
// ...

【问题讨论】:

  • 您应该在发布问题之前先进行搜索。 social.msdn.microsoft.com/Forums/vstudio/en-US/…
  • 我看过这个链接。这是Binding="{Binding}",我不知道如何创建。
  • trigger.Binding = new Binding("."); 应该是等价的。但是,这和Binding="{Binding}" 在 DataTrigger 上都没有意义,因为它缺少可以更新并因此触发触发器的源属性。
  • 没有路径(或值为“.”的路径)的绑定(在 XAML 中创建)仍将 DataContext 作为隐含源。并且 DC 可以从 null 变为 not null。所以在 XAML 中它可以工作 - 在 DataContextChanged 事件上。在后面的代码中,我认为 Source 必须是主动的、显式设置的,否则触发器的 Source 为 no Source 或 null 并且条件将始终为 true。
  • 可能是当触发器被添加到 FrameworkElement 的样式并因此成为可视化树的一部分时,当前的 DataContext 也可能自动成为(触发器绑定的)源。正如他们所说,测试高于学习。

标签: c# wpf xaml data-binding datatrigger


【解决方案1】:

这相当于您的 XAML:

var trigger = new DataTrigger()
{
    Value = null,
    Binding = new Binding(".")
};
trigger.Setters.Add(new Setter() { Property = SomeProperty, Value = SomeValue });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-24
    • 1970-01-01
    • 1970-01-01
    • 2021-08-05
    • 1970-01-01
    • 2012-12-01
    • 2016-06-26
    相关资源
    最近更新 更多