1、 主界面使用控件,绑定命令
<ItemsControl ItemsSource="{Binding ViewServerInfos}"
Style="{StaticResource ItemControlsStyle}"
Margin="8">
<ItemsControl.ItemTemplate>
<DataTemplate>
<local:UCItem ServerIP="{Binding ViewServerIP}"
OnlineState="{Binding OnlineState}"
DelCmd="{Binding Command}"/>
</DataTemplate>
//ViewServerInfo类定义如下
public class ViewServerInfo
{
public string ViewServerIP { get; set; }
public int ViewServerPort { get; set; }
public bool OnlineState { get; set; }
public string UserName { get; set; }
public string UserPwd { get; set; }
public RelayCommand<string> Command { get; set; }
public event Action<string> DelEvent;
public ViewServerInfo()
{
Command = new RelayCommand<string>(e =>
{
DelEvent?.Invoke(ViewServerIP);
});
}
}
2、 主程序中对事件的绑定
result.DelEvent += Result_DelEvent; //添加ViewServerInfo时即进行绑定
3、 自定义控件命令绑定时,一定要在自定义控件生成时,声明有此项
public RelayCommand<string> DelCmd
{
get { return (RelayCommand<string>)GetValue(DelCmdProperty); }
set { SetValue(DelCmdProperty, value); }
}
public static readonly DependencyProperty DelCmdProperty =
DependencyProperty.Register("DelCmd", typeof(RelayCommand<string>), typeof(UCItem), new PropertyMetadata(null));
private void Button_Click(object sender, RoutedEventArgs e)
{
DelCmd?.Execute(ServerIP);
}
//点击按钮时触发此命令,然后触发绑定的命令,然后触发事件进行删除