答案 0 :(得分:2)
我制作了一个简单的示例来指导您如何完成
Xaml代码
<DataGrid x:Name="dataGrid" IsEnabled="True" CanUserAddRows="False" AutoGenerateColumns="False" Width="275" HorizontalAlignment="Left">
<DataGrid.Columns>
<DataGridTextColumn Header="ID" Binding="{Binding ID}" Width="25"/>
<DataGridTextColumn Header="Weight" Binding="{Binding Weight}" Width="25"/>
<DataGridTextColumn Header="Quantity" Binding="{Binding Quantity}" Width="25"/>
<DataGridTemplateColumn Header="Length" Width="25">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding Length, UpdateSourceTrigger=LostFocus}">
<TextBox.Style>
<Style TargetType="{x:Type TextBox}">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=Length}" Value="0">
<Setter Property="BorderBrush" Value="Red"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Header="Height" Binding="{Binding Height}" Width="25"/>
<DataGridTextColumn Header="Width" Binding="{Binding Width}" Width="25"/>
<DataGridTextColumn Header="X" Binding="{Binding X}" Width="25"/>
<DataGridTextColumn Header="Y" Binding="{Binding Y}" Width="25"/>
<DataGridTextColumn Header="Z" Binding="{Binding Z}" Width="25"/>
</DataGrid.Columns>
</DataGrid>
背后的代码
public partial class MainWindow : Window
{
public ObservableCollection<Model> Source { get; set; }
public MainWindow()
{
InitializeComponent();
Source = new ObservableCollection<Model>
{
new Model {ID=1,Weight=3,Quantity=5,Length=11,Height=12,Width=0,X=1,Y=-1,Z=-1 },
new Model {ID=2,Weight=21,Quantity=23,Length=0,Height=23,Width=11,X=-1,Y=-1,Z=-1 }
};
dataGrid.ItemsSource = Source;
}
}
修改强>
只需在UpdateSourceTrigger
TextBox
中添加DataTemplate
即可