WPF 中的自定义控件

Custom Controls in WPF

构建需要有两个按钮的自定义用户控件以在 WPF 中使用是否可行?

我需要为用户提供单击两个按钮选项之一的选项。

自定义控件将根据应用程序变量加载,以代替其他控件。

具体来说,我想问的是用户控件上的功能或两个按钮,以及能够使用 WPF 中的点击事件,我对此还比较陌生。

我可以很容易地读取控件上的控件,我只是在判断是否有点击时遇到问题。

    Dim frmBtns As ControlCollection = SplitTopRight.Controls
    Dim cntrl As Windows.Forms.Control

    For Each cntrl In frmBtns
        If cntrl.Name = "btnAuto" Then
            VinDecoderUS.USVehInfo.sTransmission = "AUTO"
        ElseIf cntrl.Name = "btnManual" Then
            VinDecoderUS.USVehInfo.sTransmission = "MANUAL"
        End If
    Next    

下面的更新示例:

  1. MainWindow.xaml:

    <Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid> <ItemsControl ItemsSource="{Binding Commands}"> <ItemsControl.ItemTemplate> <DataTemplate> <Button Margin="4" Content="{Binding Name}" Command="{Binding Command}"></Button> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> </Grid> </Window>

MainWindow.xaml.cs:

  public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new MainViewModel();
    }
}

MainViewModel.cs:

  public class CommandViewModel
{
    public ICommand Command { get; set; }
    public string Name { get; set; }

}
public class MainViewModel
{
    public MainViewModel()
    {
        Commands = new List<CommandViewModel>
        {
            new CommandViewModel()
            {
                Command = new DelegateCommand() {ExecuteDelegate = o => MessageBox.Show("I am command one!!!")},
                Name = "Command one"
            },
             new CommandViewModel()
            {
                Command = new DelegateCommand() {ExecuteDelegate = o => MessageBox.Show("I am command two!!!")},
                Name = "Command two"
            }
        };
    }

    public List<CommandViewModel> Commands { get; set; }
}

public class DelegateCommand:ICommand
{
    public bool CanExecute(object parameter)
    {
        if (this.CanExecuteDelegate != null)
        {
            return this.CanExecuteDelegate(parameter);
        }
        return true;
    }

    public Func<object,bool> CanExecuteDelegate { get; set; }
    public Action<object> ExecuteDelegate { get; set; }

    public void Execute(object parameter)
    {
        if (ExecuteDelegate != null)
        {
            ExecuteDelegate(parameter);
        }
    }

    public event EventHandler CanExecuteChanged;
}