2010-12-09 67 views
2

我有一个绑定到一个DataTableDataGridDataGrid有改变数字的根据其值的细胞(正黑色或负红色)Foreground一个cellstyle。 当DataTable得到更新时,DataGrid正确更新,所以绑定工作正常。 问题在于Style仅适用于第一次加载DataGrid时。当通过绑定更新DataGrid时,如果负数变为正数,则Foreground将保持红色而不是变黑。刷新风格必然数据表WPF

我错过了什么,任何propery或事件?

在此先感谢。

+0

如果您提供一些重现问题的示例代码,我们可以更轻松地帮您解答问题 – 2010-12-09 22:26:48

回答

1

我不知道你是如何尝试做this.Any方式我都试过,它正在fine.Check这个代码,并找出什么错误

的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> 

并在您的代码隐藏

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"); 
    } 
} 

也该转换器

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 
}