Refresh style in datagrid bound to datatable WPF
I have a DataGrid
bound to a DataTable
and the DataGrid
has a cellstyle that changes the Foreground
of the numbers in the cells depending on its value (positive-black or negative-red).
When the DataTable
gets updated, the DataGrid
is properly updated, so the binding is working fine.
The problem is that the Style
is just applied when the DataGrid
is loaded the first time. When the DataGrid
gets updated by the binding, if a negative number becomes a positive one, the Foreground
remains red instead of becoming black.
Am I missing something, any propery or event?
Thanks in advance开发者_开发技巧.
I am not sure how are you trying to do this.Any way i have tried and it is working fine.Check this code and find out what is going wrong
Xaml:
<StackPanel Loaded="StackPanel_Loaded" >
<StackPanel.Resources>
<WpfApplication50:ValueToForegroundColorConverter x:Key="valueToForegroundColorConverter"/>
<DataTemplate x:Key="Valuetemplate">
<TextBlock x:Name="txt" Text="{Binding Value}" Foreground="{Binding Path=Value,Converter={StaticResource valueToForegroundColorConverter}}"/>
</DataTemplate>
</StackPanel.Resources>
<dtgrd:DataGrid ItemsSource="{Binding Source}"
Name="datagrid"
ColumnHeaderHeight="25"
AutoGenerateColumns="False"
>
<dtgrd:DataGrid.Columns>
<dtgrd:DataGridTemplateColumn CellTemplate="{StaticResource Valuetemplate}" Header="Value"/>
</dtgrd:DataGrid.Columns>
</dtgrd:DataGrid>
<Button Height="30" Click="Button_Click"/>
</StackPanel>
and in your codebehind
public partial class Window10 : Window,INotifyPropertyChanged
{
private DataTable source;
public DataTable Source
{
get { return source; }
set { source = value; OnPropertyChanged("Source"); }
}
public Window10()
{
InitializeComponent();
this.DataContext = this;
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string name)
{
if(PropertyChanged!=null)
PropertyChanged(this,new PropertyChangedEventArgs(name));
}
#endregion
private void Button_Click(object sender, RoutedEventArgs e)
{
Source.Rows.Add("-1");
}
private void StackPanel_Loaded(object sender, RoutedEventArgs e)
{
Source = new DataTable();
Source.Columns.Add("Value");
Source.Rows.Add("1");
}
}
also this converter
class ValueToForegroundColorConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
SolidColorBrush brush = new SolidColorBrush(Colors.Black);
int val = 0;
int.TryParse(value.ToString(), out val);
if (val < 0)
brush = new SolidColorBrush(Colors.Red);
return brush;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
精彩评论