WPF 选项卡控件.绑定按钮到具有 CanExecute 条件的命令位于子视图中



这是这样的场景:在用户控件中有一个TabControl,它加载不同的视图,还有一个按钮。像这张图片:

场景

仅当字段"名称"和"所有者"不为空时,才能启用"保存"按钮。这些字段位于 ItemTab 中加载的子视图中。

这是 XAML(仅具有 1 个选项卡项以简化)

<UserControl 
    x:Class="Winvet.Desktop.Views.VCliente.DatosCliente"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    mc:Ignorable="d" 
    xmlns:viewModels="clr-namespace:Winvet.Desktop.ViewModels.VMCliente"
    xmlns:views="clr-namespace:Winvet.Desktop.Views.VCliente">
    <Grid Margin="10 5 10 10">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="7*"/>
            <ColumnDefinition Width="3*"/>
        </Grid.ColumnDefinitions>
        <TabControl Grid.Column="0" Name="TabDatosCliente" ItemsSource="{Binding ItemsTabDatosCliente}" SelectedIndex="0">
            <TabControl.Resources>
                <DataTemplate DataType="{x:Type viewModels:DatosClienteGeneralViewModel}">
                    <views:DatosClienteGeneral/>
                </DataTemplate>
            </TabControl.Resources>
            <TabControl.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Header}" />
                </DataTemplate>
            </TabControl.ItemTemplate>  
        </TabControl>
        <StackPanel Grid.Column="1" Orientation="Horizontal">
            <Button VerticalAlignment="Bottom" Command="{ I want to bind this }">Guardar</Button>
        </StackPanel>
    </Grid>
</UserControl>

这是视图模型(只有 1 个选项卡项要简化)

using System.Collections.ObjectModel;
using Winvet.Desktop.Common;
namespace Winvet.Desktop.ViewModels.VMCliente
{
    public class DatosClienteViewModel: ViewModelBase
    {                 
        public ObservableCollection<ViewModelBase> ItemsTabDatosCliente { get; private set; }
        public DatosClienteViewModel()
        {
            ItemsTabDatosCliente = new ObservableCollection<ViewModelBase>
            {
                new DatosClienteGeneralViewModel()
            };
        }
    }
}

我不想创建一个命令来检查这两个子视图字段是否不为空并启用按钮。我该怎么做?

路由命令在整个界面中挖洞和冒泡,因此只要您与引发事件的项目位于同一视觉分支中,您就可以在任何地方处理它。

所以在你的视野中

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        CommandBindings.Add(new CommandBinding(command, execute, canExecute));
    }
    private void canExecute(object sender, CanExecuteRoutedEventArgs e)
    {
        throw new NotImplementedException();
        //at this point you can pass it to your ViewModel
    }
    private void execute(object sender, ExecutedRoutedEventArgs e)
    {
        throw new NotImplementedException();
        //at this point you can pass it to your ViewModel
    }
}

其中命令是在按钮上设置的路由命令 命令属性

最新更新