2017-09-06 24 views
0

我有一個窗口綁定到視圖模型。該窗口包含多個用戶控件。我想將其中一個用戶控件的不透明度綁定到Windows視圖模型中公開的屬性。通過綁定設置嵌入窗口中的usercontrol的opactity

任何想法?

這裏是我的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}" /> 

這裏是我的窗口視圖模型的一個片段:

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"); 
      }; 
     } 
    } 
} 

任何想法? 感謝

回答

5

這應該工作:

<Controls:SoundControl x:Name="soundControl" Style="{StaticResource DeviceControlStyle}" Opacity="{Binding DataContext.SoundControlOpacity, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}"> 
+1

對不起,延遲響應。我不得不應對颶風伊爾瑪。 您的建議很好地工作。正是我在找什麼 - 謝謝! –

0

您可以綁定到從父控件公開的屬性,就像sTrenat解釋,但我相信,有以達到同樣的目標更加maintanable方式。

如果我理解正確,嵌套在窗口中的UserControls擁有自己的ViewModel,並且它們的實例被保存在WindowViewModel中。在這種情況下,我建議你創建一個包含ControlOpacity屬性的類,並在你的UserControlViewModel中派生它。然後將sholud綁定到UserControlView中的UserControl的不透明屬性(而不是WindowView中)。您可以通過將值分配給UserControlViewModel.ControlOpacity,從UserControlViewModel或WindowViewModel更改其值。

通過這種方式,您不會違反單個責任規則,並且您的問題(您可以輕鬆地在其他控件中重複使用)具有更靈活和更靈活的解決方案。

相關問題