因爲在的ItemsSource DataGrid中每個元素的運行時創建它自己的TextBlock和CheckBox你不能有綁定到該元素的名稱。相反,您應該將複選框的值和TextBlock的樣式設置器綁定到您的模型。例如,你有模型和視圖模型是這樣的:
型號:
public class SomeModel : INotifyPropertyChanged
{
private string textField;
private bool boolField;
public event PropertyChangedEventHandler PropertyChanged;
public string TextField
{
get { return textField; }
set
{
if (value == textField) return;
textField = value;
OnPropertyChanged();
}
}
public bool BoolField
{
get { return boolField; }
set
{
if (value.Equals(boolField)) return;
boolField = value;
OnPropertyChanged();
}
}
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
視圖模型:所以現在
public class MainViewModel : INotifyPropertyChanged
{
private ObservableCollection<SomeModel> models;
public ObservableCollection<SomeModel> Models
{
get { return models; }
set
{
if (Equals(value, models)) return;
models = value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
public MainViewModel()
{
Models = new ObservableCollection<SomeModel>();
}
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
可以綁定模型的BoolField到複選框的值和TextBlock的風格二傳手在查看:
MainView.cs:
public partial class MainView : Window
{
public MainView()
{
InitializeComponent();
var mv = new MainViewModel
{
Models = { new SomeModel { BoolField = true, TextField = "One" }, new SomeModel { TextField = "Two" } },
};
DataContext = mv;
}
}
MainView.xaml:
<Window x:Class="WpfDataGridCols.MainView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainView" Height="350" Width="525">
<Grid>
<DataGrid ItemsSource="{Binding Models}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding TextField}">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="TextWrapping" Value="Wrap"/>
<Setter Property="TextAlignment" Value="Center" />
<Style.Triggers>
<!--Pay attention on this:-->
<DataTrigger Binding="{Binding BoolField}" Value="True">
<Setter Property="TextDecorations" Value="Strikethrough"/>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridCheckBoxColumn Binding="{Binding BoolField}"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
的複選框柱後代碼。 –