在我的datagrid上,我有一个DataTrigger,用于确定将前景(Text)设置为哪种颜色。该值存储为我的页面的属性。
我已经很好地完成了这项工作,但现在我正在为用户提供自行设置此颜色的功能。
我的问题是当用户设置此颜色并更新属性时,如何使数据网格现在反映此更改。
我在下面做的例子(PrivateMessages以不同的颜色显示)
<DataTrigger Binding="{Binding Path=IsPrivate}" Value="True">
<Setter Property="Foreground" Value="{Binding ElementName=GridPage, Path=PrivateMessageColour}" />
</DataTrigger>
非常感谢任何帮助或指导。
提前致谢。
答案 0 :(得分:0)
确保您的类型实现了INotifyPropertyChanged界面,并在修改颜色时DataTrigger
绑定到公开的属性的setter上触发更改通知。
编辑:以下是使用TextBox
和Button
更改颜色的示例...
C#:
public partial class Window1 : Window
{
MyData _data = new MyData();
public Window1()
{
InitializeComponent();
this.DataContext = _data;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
_data.ChangeColor();
}
}
public class MyData : INotifyPropertyChanged
{
Random _rand = new Random();
List<String> _colors = new List<string> { "Red", "Black", "Blue" };
public void ChangeColor()
{
MyColor = _colors[_rand.Next(0, 3)];
}
private bool _isActive = true;
public bool IsActive
{
get
{
return _isActive;
}
set
{
_isActive = value;
PropertyChangedEventHandler h = PropertyChanged;
if (h != null)
h(this, new PropertyChangedEventArgs("IsActive"));
}
}
private String _myColor = "Green";
public String MyColor
{
get
{
return _myColor;
}
set
{
_myColor = value;
PropertyChangedEventHandler h = PropertyChanged;
if (h != null)
h(this, new PropertyChangedEventArgs("MyColor"));
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
}
}
XAML:
<Grid>
<Button Height="25" Click="Button_Click" Content="Change Color" VerticalAlignment="Bottom" />
<TextBox Width="200" Height="100">
<TextBox.Style>
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding IsActive}" Value="true">
<Setter Property="TextBox.Background" Value="{Binding MyColor}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
</Grid>