WPF:Command传递两个元素
程序员文章站
2022-06-07 14:25:33
...
//MainWindow.xaml
<Window x:Class="Command_MultiElement.MainWindow"
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"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:local="clr-namespace:Command_MultiElement"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:MultiParamterConverter x:Key="MultiConverter"/>
</Window.Resources>
<StackPanel>
<Button x:Name="button0" Content="button0" Height="50"/>
<Button x:Name="button1" Content="button1" Height="50"/>
<Button x:Name="change" Content="change" Height="50" Command="{Binding ChangeClickCommand}">
<Button.CommandParameter>
<MultiBinding Converter="{StaticResource MultiConverter}">
<Binding ElementName="button0"/>
<Binding ElementName="button1"/>
</MultiBinding>
</Button.CommandParameter>
</Button>
</StackPanel>
</Window>
//MainWindow.xaml.cs
using System;
using System.Windows;
using System.Windows.Data;
using System.Globalization;
namespace Command_MultiElement
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new ViewModel();
}
}
public class MultiParamterConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
//必须新new一个,否则拿不到数据,因为values在返回之后,就会被清空了
return values.Clone();
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
//ViewModel.cs
using Microsoft.Practices.Prism.Commands;
using Microsoft.Practices.Prism.Mvvm;
using System;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
namespace Command_MultiElement
{
public class ViewModel : BindableBase
{
#region ChangeClickCommand
DelegateCommand<object> changeClickCommand = null;
public ICommand ChangeClickCommand
{
get
{
if (changeClickCommand == null)
{
changeClickCommand = new DelegateCommand<object>((p) => OnChangeClick(p), (p) => CanChangeClick(p));
}
return changeClickCommand;
}
}
private bool CanChangeClick(object parameter)
{
return true;
}
private void OnChangeClick(object parameter)
{
Console.WriteLine("OnChangeClick");
var values = (object[])parameter;
var btn0 = (Button)values[0];
var btn1 = (Button)values[1];
btn0.Background = Brushes.Blue;
btn1.Background = Brushes.Brown;
}
#endregion
}
}
点击一个按钮,通过Command传递另外两个按钮,并修改另外两个按钮的背景
效果图:
完整工程:
上一篇: 修改第三方组件样式
推荐阅读