wpf 实现用户控件 按钮带参数命令
时间: 2023-10-09 11:10:18 浏览: 72
要实现一个带参数命令的用户控件,您可以使用 WPF 中的 User Control,并在该控件内部添加一个 Button 控件。然后,您可以在 User Control 中实现 ICommandSource 接口,使您的控件支持命令。下面是一个简单的示例,演示如何实现一个带参数命令的用户控件:
1.创建一个 User Control,例如 MyButtonControl。
2.在 MyButtonControl 中添加一个 Button 控件,并设置 Button 的 Content 属性和 Command 属性,如下所示:
```xml
<UserControl x:Class="WpfApp1.MyButtonControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<Grid>
<Button Content="{Binding Text}" Command="{Binding Command}" CommandParameter="{Binding CommandParameter}"/>
</Grid>
</UserControl>
```
注意,在这个例子中,我们使用了 Binding 来绑定 Text 属性、Command 属性和 CommandParameter 属性。这些属性将在后面的代码中定义。
3.在 MyButtonControl 中实现 ICommandSource 接口,如下所示:
```csharp
public partial class MyButtonControl : UserControl, ICommandSource
{
public MyButtonControl()
{
InitializeComponent();
}
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(MyButtonControl), new PropertyMetadata("Button"));
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
public static readonly DependencyProperty CommandProperty =
DependencyProperty.Register("Command", typeof(ICommand), typeof(MyButtonControl), new PropertyMetadata(null));
public ICommand Command
{
get { return (ICommand)GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}
public static readonly DependencyProperty CommandParameterProperty =
DependencyProperty.Register("CommandParameter", typeof(object), typeof(MyButtonControl), new PropertyMetadata(null));
public object CommandParameter
{
get { return GetValue(CommandParameterProperty); }
set { SetValue(CommandParameterProperty, value); }
}
}
```
在这个例子中,我们定义了三个依赖属性:Text、Command 和 CommandParameter 属性,这些属性将在前面的 XAML 代码中使用。
4.在您的 View 中使用 MyButtonControl,如下所示:
```xml
<Window x:Class="WpfApp1.MainWindow"
xmlns:local="clr-namespace:WpfApp1"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="450" Width="800"
mc:Ignorable="d">
<Grid>
<local:MyButtonControl Text="Click Me!" Command="{Binding MyCommand}" CommandParameter="parameter" />
</Grid>
</Window>
```
在这个例子中,我们使用了 MyButtonControl,并为 Text、Command 和 CommandParameter 属性设置了值。当用户单击 MyButtonControl 中的 Button 时,Command 将被执行,并且 CommandParameter 将被传递给 Execute 方法。