WPF DataTemplate 中绑定非ItemsSource资源

在WPF中使用ListView,DataGrid时经常要动态加载控件,例如TextBox,Button等。当为这些控件绑定Command时由于会继承上级控件(ListView,DataGrid等)的DataContext,想要绑定ViewModel里面的Command要做些处理。我们先看代码

  1. 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>

  1. 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>

源码地址

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

pluto li

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值