在WPF中使用ListView,DataGrid时经常要动态加载控件,例如TextBox,Button等。当为这些控件绑定Command时由于会继承上级控件(ListView,DataGrid等)的DataContext,想要绑定ViewModel里面的Command要做些处理。我们先看代码
- Xaml代码
<Window x:Class="WpfMVVM.Views.MainView"
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:local="clr-namespace:WpfMVVM.Views"
xmlns:sys="clr-namespace:System.Configuration.Assemblies;assembly=System.Runtime"
xmlns:viewmodels="clr-namespace:WpfMVVM.ViewModels"
xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
d:DataContext="{d:DesignInstance Type=viewmodels:MainViewModel}"
mc:Ignorable="d" WindowStartupLocation="CenterScreen"
Title="MainView" Height="450" Width="800" x:Name="window_name">
<Grid>
<Button Content="按钮命令" Command="{Binding ButtonCommand}" HorizontalAlignment="Left" Margin="109,51,0,0" VerticalAlignment="Top" Width="86" Height="30"/>
<Button Content="关闭命令" Command="{Binding CloseCommand}" CommandParameter="{Binding ElementName=window_name}" HorizontalAlignment="Left" Margin="251,51,0,0" VerticalAlignment="Top" Width="97" Height="30"/>
<TextBox x:Name="textbox_name" HorizontalAlignment="Left" Margin="109,126,0,0" Text="{Binding TextOfBox}" TextWrapping="Wrap" VerticalAlignment="Top" Width="147" Height="25">
<TextBox.InputBindings>
<MouseBinding Command="{Binding TextBoxClickCommand}" CommandParameter="{Binding ElementName=textbox_name}" MouseAction="LeftClick"></MouseBinding>
</TextBox.InputBindings>
</TextBox>
<DataGrid x:Name="data_grid" Margin="0,171,0,0" ItemsSource="{Binding list}" CanUserAddRows="False" AutoGenerateColumns="False" IsReadOnly="True" >
<DataGrid.Resources>
<DataTemplate x:Key="col0">
<TextBox Text="{Binding Col0}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="PreviewMouseDown">
<i:InvokeCommandAction Command="{Binding DataContext.ListTextBoxClickCommand, RelativeSource={RelativeSource AncestorType=Window}}" CommandParameter="{Binding Path=.,RelativeSource={RelativeSource AncestorType=TextBox}}"></i:InvokeCommandAction>
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBox>
</DataTemplate>
<DataTemplate x:Key="col1">
<TextBox Text="{Binding Col1}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="PreviewMouseDown">
<i:InvokeCommandAction Command="{Binding DataContext.ListTextBoxClickCommand, RelativeSource={RelativeSource AncestorType=Window}}" CommandParameter="{Binding Path=.,RelativeSource={RelativeSource AncestorType=TextBox}}"></i:InvokeCommandAction>
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBox>
</DataTemplate>
<DataTemplate x:Key="col2">
<TextBox Text="{Binding Col2}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="PreviewMouseDown">
<i:InvokeCommandAction Command="{Binding DataContext.ListTextBoxClickCommand, RelativeSource={RelativeSource AncestorType=Window}}" CommandParameter="{Binding Path=.,RelativeSource={RelativeSource AncestorType=TextBox}}"></i:InvokeCommandAction>
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBox>
</DataTemplate>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTemplateColumn Header="Col0" CellTemplate="{StaticResource col0}"></DataGridTemplateColumn>
<DataGridTemplateColumn Header="Col1" CellTemplate="{StaticResource col1}"></DataGridTemplateColumn>
<DataGridTemplateColumn Header="Col2" CellTemplate="{StaticResource col2}"></DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
- ViewModel代码
using Microsoft.Toolkit.Mvvm.ComponentModel;
using Microsoft.Toolkit.Mvvm.Input;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using WpfMVVM.Models;
using WpfMVVM.Services;
namespace WpfMVVM.ViewModels
{
public class MainViewModel:ObservableObject
{
public RelayCommand ButtonCommand { set; get; }
public RelayCommand<Window> CloseCommand { set; get; }
public RelayCommand<TextBox> TextBoxClickCommand { set; get; }
public RelayCommand<TextBox> ListTextBoxClickCommand { set;get; }
private string _TextOfBox = "文本框点击命令";
public string TextOfBox
{
set => SetProperty(ref _TextOfBox, value);
get => _TextOfBox;
}
public ObservableCollection<ListModel> list { get; } = new ObservableCollection<ListModel>();
protected readonly ITestService _testService;
public MainViewModel(ITestService testService)
{
ButtonCommand = new RelayCommand(OnButtonCommand);
CloseCommand = new RelayCommand<Window>(OnCloseCommand);
TextBoxClickCommand = new RelayCommand<TextBox>(OnTextBoxClickCommand);
ListTextBoxClickCommand = new RelayCommand<TextBox>(OnListTextBoxClickCommand);
_testService = testService;
for (int i = 0; i < 10; i++)
{
list.Add(new ListModel
{
Col0 = i.ToString(),
Col1 = i,
Col2 = true
});
}
}
private void OnListTextBoxClickCommand(TextBox obj)
{
obj.Text = "123";
}
private void OnTextBoxClickCommand(TextBox obj)
{
obj.Text = "点击了文本框";
}
private void OnCloseCommand(Window obj)
{
if(MessageBox.Show("要关闭吗?","提示",MessageBoxButton.YesNo)!= MessageBoxResult.Yes)
{
return;
}
obj.Close();
}
private void OnButtonCommand()
{
_testService.Test();
}
}
}
下面代码中RelativeSource={RelativeSource AncestorType=Window}是找到类型为Window的控件作为绑定源,只有页面本身才是Window类型的,然后再通过DataContext.ListTextBoxClickCommand获取数据上下文获取相应的Command。
<i:InvokeCommandAction Command="{Binding DataContext.ListTextBoxClickCommand, RelativeSource={RelativeSource AncestorType=Window}}" CommandParameter="{Binding Path=.,RelativeSource={RelativeSource AncestorType=TextBox}}"></i:InvokeCommandAction>