【问题标题】:WPF xaml DataTrigger binding not workingWPF xaml DataTrigger 绑定不起作用
【发布时间】:2014-09-09 23:39:21
【问题描述】:

我使用 xaml 和 C# 创建了一个简单的应用程序,它将边框颜色绑定到布尔方法 IsToday 后面的代码。但不知何故,它不起作用。

有人可以帮忙吗?我也尝试过INotifyPropertyChanged,但它不起作用。如果有人可以提供帮助,不胜感激,谢谢!

后面的代码:

namespace WpfApplication3
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            IsToday = true;
            InitializeComponent();
        }

        public bool IsToday { get; set; }
    }
}

XAML

<Window x:Class="WpfApplication3.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">
    <Window.Resources>
        <ResourceDictionary Source="Dictionary1.xaml">
        </ResourceDictionary>
    </Window.Resources>
        <Grid>
        <Border Style="{StaticResource Highlight}">
        </Border>
    </Grid>
</Window>

XAML 字典

 <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
        <Style TargetType="Border" x:Key="Highlight">
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsToday}" Value="True">
                    <Setter Property="Background" Value="Red"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding IsToday}" Value="False">
                    <Setter Property="Background" Value="Blue"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </ResourceDictionary>

【问题讨论】:

    标签: wpf xaml data-binding binding datatrigger


    【解决方案1】:

    你必须为你的Window设置DataContext

     public MainWindow() {
          InitializeComponent();
          DataContext = this;
          IsToday = true;
     }
    

    当然,这只是最初,之后对IsToday 所做的所有更改都将不起作用。如您所知,我们必须实现INotifyPropertyChanged

    【讨论】:

      【解决方案2】:

      您可以从 xaml 中设置上下文。

      <Window x:Class="WpfApplication3.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"
              DataContext="{Binding RelativeSource={RelativeSource Self}}">
          <!-- your code -->
      </Window>
      

      【讨论】:

        猜你喜欢
        • 2013-10-19
        • 2014-05-28
        • 1970-01-01
        • 2021-11-14
        • 2016-04-10
        • 1970-01-01
        • 1970-01-01
        • 2013-09-24
        • 2020-11-01
        相关资源
        最近更新 更多