I have 开发者_开发技巧created a 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>
The Person
class looks like this:
public class Person
{
public string Image { get; set; }
}
The presented data trigger in the data template does not work as expected. No matter if I provide the value for the Image
property or not, it simply won't draw the linear gradient brush background. On the other hand, the text block is showing the content of the Image
property as it should.
I thought that maybe when the person.Image = null;
, then the XAML is in fact reading it as person.Image = string.Empty;
but I tried replacing Value="{x:Null}"
with Value=""
and it still doesn't work.
Help please, thanks.
Try implementing Change Notification on your Person class. That might be the cause of your problem.
The binding is correct, but you don't see anything because your Border
is 0×0 px. You can get the desired effect like this:
<Border Width="50">
<TextBlock Text="{Binding Image}" />
<!-- your style unchanged -->
</Border>
As AbdouMoumen has suggested, implement INotifyPropertyChanged on your Person class.
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));
}
}
}
Then only setting person.Image = null will have effect on your xaml.
精彩评论