在开发中,有时候会遇到在DataGrid的ItemsSource对象中添加委托事件的需求:比如DataGrid的表格中有对应的选择事件,当点击选择事件时,会进行触发别的事件,这个时候可以添加委托来进行处理。用方法的话,需要在每个对象都写方法,很不合理,而且对象应该是封装的,违法了设计原则…
xaml
<DataGrid AutoGenerateColumns="False" IsReadOnly="True" ItemsSource="{Binding GasDrawDataWrapper}" AlternationCount="2" CanUserAddRows="False" ColumnHeaderHeight="28"
HeadersVisibility="Column" ScrollViewer.HorizontalScrollBarVisibility="Auto" ScrollViewer.VerticalScrollBarVisibility="Auto" ScrollViewer.CanContentScroll="True">
<DataGrid.Columns>
<DataGridTemplateColumn >
<DataGridTemplateColumn.HeaderTemplate >
<DataTemplate>
<Label Content="Gas" FontSize="14" Margin="5,0,0,0" Height="28" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" />
</DataTemplate>
</DataGridTemplateColumn.HeaderTemplate>
<DataGridTemplateColumn.CellTemplate >
<DataTemplate>
<WrapPanel>
<RadioButton Margin="5,0,0,0" IsChecked="{Binding IsDraw,Mode=TwoWay}" Command="{Binding CheckBoxCommand}" HorizontalAlignment="Center" VerticalAlignment="Center">
</RadioButton>
<Label Content="{Binding GasAll}" Margin="5,0,0,0" />
</WrapPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
后台
public class GasDraw : NotifyPropertyBase
{
private string gas;
private string gasAll;
private bool isDraw;
/// <summary>
/// GasDraw Filed
/// </summary>
public string Gas
{
get { return gas; }
set
{
gas = value;
OnPropertyChanged("Gas");
}
}
/// <summary>
/// GasDraw Filed
/// </summary>
public string GasAll
{
get { return gasAll; }
set
{
gasAll = value;
OnPropertyChanged("GasAll");
}
}
/// <summary>
/// GasDraw Filed
/// </summary>
public bool IsDraw
{
get { return isDraw; }
set
{
isDraw = value;
OnPropertyChanged("IsDraw");
}
}
/// <summary>
///
/// </summary>
public Action CallBackAction { get; set; }
/// <summary>
/// Command to DrawRadioCommand of PartialPressureScreen
/// </summary>
public ICommand CheckBoxCommand
{
get { return new DelegateCommand { CommandAction= ExecutionDrawRadioCommand }; ; }
}
private void ExecutionDrawRadioCommand()
{
CallBackAction.Invoke();
}
}
在进行实例化时候可以进行委托的处理
GasDraw gasDraw = new GasDraw();
gasDraw.CallBackAction = callBackAction;
private void callBackAction()
{
}
上述操作,可以在委托时候,当页面点击Command="{Binding CheckBoxCommand}"时,会触发gasDraw.CallBackAction = callBackAction;,执行想要进行的操作。如果不用委托,则需要在list的每个对象中都创建一个方法,在接口中去写,不满足对应的设计模式的六大原则中的依赖倒置和接口隔离原则。
如果帮到了你,请关注一波,谢谢