【问题标题】:WPF: Fire data trigger when the value of the string is null or string.EmptyWPF:当字符串的值为 null 或 string.Empty 时触发数据触发器
【发布时间】:2011-08-11 14:13:43
【问题描述】:

我创建了一个DataTemplate

<DataTemplate DataType="{x:Type model:Person}">
  <StackPanel>
    <!-- Text box is binding to the person's Image property. -->
    <TextBlock Text="{Binding Image}" />
    <Border>
      <Border.Style>
        <Style TargetType="Border">
          <Style.Triggers>
            <!-- Data trigger is binding to the same Image property. -->
            <DataTrigger Binding="{Binding Image}" Value="{x:Null}">
              <Setter Property="Background">
                <Setter.Value>
                  <LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
                    <GradientStop Color="#696969" Offset="0.0" />
                    <GradientStop Color="#2E2E2E" Offset="1.0" />
                  </LinearGradientBrush>
                </Setter.Value>
              </Setter>
            </DataTrigger>
          </Style.Triggers>
        </Style>
      </Border.Style>
    </Border>
  </StackPanel>
</DataTemplate>

Person 类如下所示:

public class Person
{
    public string Image { get; set; }
}

数据模板中显示的数据触发器未按预期工作。无论我是否提供Image 属性的值,它都不会绘制线性渐变画笔背景。另一方面,文本块正按应有的方式显示Image 属性的内容。

我认为也许当person.Image = null; 时,XAML 实际上将其读取为person.Image = string.Empty;,但我尝试将Value="{x:Null}" 替换为Value="",但它仍然不起作用。

请帮忙,谢谢。

【问题讨论】:

    标签: wpf xaml triggers datatrigger


    【解决方案1】:

    尝试在您的 Person 类上实现更改通知。这可能是您的问题的原因。

    【讨论】:

      【解决方案2】:

      绑定是正确的,但是您看不到任何内容,因为您的 Border 是 0×0 像素。你可以像这样得到想要的效果:

      <Border Width="50">
          <TextBlock Text="{Binding Image}" />
          <!-- your style unchanged -->
      </Border>
      

      【讨论】:

      • 我添加了边框宽度和高度属性。我什至添加了Background="Red" 属性,但红色不会变成线性渐变。或许您还有其他建议?
      • 这很奇怪,对我来说就是这样。虽然只适用于null,而不适用于空字符串。
      【解决方案3】:

      正如 AbdouMoumen 所建议的,在您的 Person 类上实现 INotifyPropertyChanged。

      public class Person : INotifyPropertyChanged
      {
          private string _image;
          public string Image
          {
              get { return _image; }
              set
              {
                  _image = value;
                  NotifyPropertyChanged("Image");
              }
          }
      
          public event PropertyChangedEventHandler PropertyChanged;
      
          protected void NotifyPropertyChanged(string info)
          {
              if (PropertyChanged != null)
              {
                  PropertyChanged(this, new PropertyChangedEventArgs(info));
              }
          }
      }
      

      那么只有设置 person.Image = null 才会对你的 xaml 产生影响。

      【讨论】:

        猜你喜欢
        • 2019-06-11
        • 2011-02-24
        • 2011-09-06
        • 2016-03-12
        • 1970-01-01
        • 1970-01-01
        • 2021-12-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多