通过绑定设置嵌入在窗口中的usercontrol的可操作性

Her*_*mos 0 c# wpf xaml

我有一个绑定到视图模型的窗口.该窗口包含多个用户控件.我想将其中一个用户控件的不透明度绑定到在Windows视图模型中公开的属性.

有任何想法吗?

这是我的XAML的片段:

<Window xmlns:Controls="clr-namespace:xxx.UI.Controls"  x:Class="xxx.xxx.UI.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:local="clr-namespace:xxx.xxx.UI"
    xmlns:viewModels="clr-namespace:xxx.xxx.UI.ViewModels;assembly=xxx.xxx.UI.ViewModels"
    mc:Ignorable="d"
    d:DesignHeight="768" 
    d:DesignWidth="1366"
    Title="MCH Anywhere" 
    Icon="Images\Icons\app-icon.ico"
    Height="{Binding SystemParameters.PrimaryScreenHeight}"
    Width="{Binding SystemParameters.PrimaryScreenWidth}"
    WindowState="Maximized">

<Window.DataContext>
    <viewModels:MainWindowViewModel/>
</Window.DataContext>

<Controls:SoundControl x:Name="soundControl" Style="{StaticResource DeviceControlStyle}" Opacity="{Binding Path=SoundControlOpacity}" />
Run Code Online (Sandbox Code Playgroud)

这是我的窗口视图模型的片段:

public class MainWindowViewModel : IMainWindowViewModel, 
        INotifyPropertyChanged 
{
    public MainWindowViewModel()
    {
        this.SoundControlOpacity = .2;  // binding does not work.
    }

    private double _soundControlOpacity;
    /// <summary>
    /// Gets or sets the opacity of the Ultrasound control.
    /// </summary>
    public double SoundControlOpacity
    {
        get { return _soundControlOpacity; }
        set
        {
            if (value != _soundControlOpacity)
            {
                _soundControlOpacity = value;
                OnPropertyChanged("SoundControlOpacity");
            };
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?谢谢

sTr*_*nat 5

这应该工作:

<Controls:SoundControl x:Name="soundControl" Style="{StaticResource DeviceControlStyle}" Opacity="{Binding DataContext.SoundControlOpacity, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}">
Run Code Online (Sandbox Code Playgroud)