我如何传递xaml控制参数,如对象,routedEventArgs到命令



我正试图找出如何使用控制参数,你有一个典型的事件处理程序,如点击使用命令。我学会了如何使用命令运行方法,但是如果

  1. 我想引用我的按钮在UI当我的方法是在一个完全不同的类?
  2. 如何获得按下控件的参数?

这是我得到的,不确定它是否专业的使用方式,希望是的:)这是绑定到控件的类和命令:

class Commands
{
    private ICommand rectangleCommand;
    public ICommand RectangleCommand
    {
        get { return rectangleCommand; } 
    }
    public Commands()
    {
        rectangleCommand = new RelayCommand(makeItInvisible);
    }
    private void makeItInvisible()
    {
        MessageDialog dialog = new MessageDialog("Works");
        dialog.ShowAsync();
    }
}

这是我的RelayCommand类实现ICommand和使用Action委托指向Commands类的方法:

public class RelayCommand : ICommand
{
    public event EventHandler CanExecuteChanged;
    private Action action;
    public RelayCommand(Action action)
    {
        this.action = action;
    }
    public bool CanExecute(object parameter)
    {
        return true;
    }
    public void Execute(object parameter)
    {
        action();
    }
}

这很好,但我需要更多。:)这是我的XAML代码。我只是创建它来练习INottifyProperyChanged和iccommand接口。让我们假设:首先,我想传递到我创建的另一个页面对象,并在OnNavigatedTo方法中使用它。另一种情况是,我希望更改已按下的按钮的一些属性。在后面的代码中使用标准事件处理程序,我可以很容易地使用对象发送器,routedEventArgs,已经传递。我如何使用命令做到这一点?

<Grid DataContext="{StaticResource Person}" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <TextBlock HorizontalAlignment="Left" Margin="808,84,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Height="85" Width="323" FontSize="25" Text="{Binding Name}"/>
    <TextBox HorizontalAlignment="Left" Margin="138,107,0,0" TextWrapping="Wrap" Text="{Binding Name,Mode=TwoWay}" VerticalAlignment="Top" Width="435"/>
    <Button Content="Button" x:Name="Button1" Margin="100,375,0,0" VerticalAlignment="Top" Height="75" Width="257" Background="#FF39349E"/>
    <Button Content="Button" x:Name="Button2" HorizontalAlignment="Left" Margin="457,375,0,0" VerticalAlignment="Top" Height="75" Width="257" Background="#FF39349E"/>
    <Button Content="Button" x:Name="Button3" HorizontalAlignment="Left" Margin="830,375,0,0" VerticalAlignment="Top" Height="75" Width="257" Background="#FF39349E"/>
    <Button Content="Show The Message" HorizontalAlignment="Left" Margin="833,242,0,0" VerticalAlignment="Top" Width="273" Height="69" Background="#FFE07031"
            DataContext="{StaticResource Commands}" Command="{Binding RectangleCommand}"/>

</Grid>

您使用CommandParameter Dependency Property来传递参数。

<Button Content="Show The Message" HorizontalAlignment="Left" Margin="833,242,0,0" VerticalAlignment="Top" Width="273" Height="69" Background="#FFE07031"
        DataContext="{StaticResource Commands}" CommandParameter"Show the message" Command="{Binding RectangleCommand}"/>

但是你想要达到的目标可能更好地通过触发来实现。您的命令不应该知道任何关于按钮或UI的信息。

最新更新