欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C#命令语句使用

程序员文章站 2022-06-07 14:25:27
...

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);
    }

//点击按钮时触发此命令,然后触发绑定的命令,然后触发事件进行删除