将可见性绑定到与DataContext不同的源

fre*_*e0n 1 .net c# wpf xaml binding

我有两个ViewModel:

public class CommandViewModel
{
    public string DisplayName { get; set; }
    public ICommand Command { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

public class SomeViewModel : INotifyPropertyChanged
{
    private bool someFlag;
    private CommandViewModel someCommand;

    public bool SomeFlag
    {
        get
        {
            return someFlag;
        }
        set
        {
            if (value == someFlag)
                return;
            someFlag = value;
            OnPropertyChanged("SomeFlag");
        }
    }

    public CommandViewModel SomeCommandViewModel
    {
        get
        {
            if (someCommand == null)
            {
                someCommand = new CommandViewModel();
                // TODO: actually set the DisplayName and Command
            }
            return someCommand;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我有两个相应的观点:

<UserControl x:Class="ButtonView"
             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" 
             d:DesignHeight="28" d:DesignWidth="91">
    <Button Content="{Binding Path=DisplayName}" Command="{Binding Path=Command}" />
</UserControl>
Run Code Online (Sandbox Code Playgroud)

<UserControl x:Class="SomeView"
    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" Height="125" Width="293" />

    <ViewButton
        Visibility="{Binding Path=SomeFlag, Converter={StaticResource BoolToVisibilityConverter}}"
        DataContext="{Binding Path=SomeCommandViewModel}" />
</UserControl>
Run Code Online (Sandbox Code Playgroud)

当我的DataContext也被绑定时,我遇到了阻止ButtonView的Visibility绑定的问题.如果我退出DataContext,Visibility工作正常(当SomeFlag切换值时,按钮的可见性随之改变) - 但显示文本和命令不起作用.如果我绑定DataContext,显示文本和命令工作,但可见性不起作用.我敢肯定,当我将DataContext绑定到SomeCommandViewModel时,它需要"SomeFlag"存在于其中.当然,事实并非如此.

Mar*_*tin 6

如果设置任何给定元素的DataContext,则此元素的每个绑定(包括子元素)将使用DataContext作为源,除非您明确给出另一个源.

你似乎要做的是一次指定2个DataContext(UserControl.DataContext不被读取,因为设置了ViewButton.DataContext并且它找到的第一个源计数).

您可以显式获取给定元素的datacontext作为Kent状态,也可以显式指定源.例如

<ViewButton
    Visibility="{Binding Path=SomeFlag, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}, Converter={StaticResource BoolToVisibilityConverter}}"
    DataContext="{Binding Path=SomeCommandViewModel}" />
Run Code Online (Sandbox Code Playgroud)