2010-12-09 66 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 
}