用户控件的依赖属性与主视图模型属性之间的绑定

时间:2016-06-17 10:26:00

标签: c# wpf

我有一些小问题。我有2个视图模型和2个相应的视图。在第一个视图(用户控件)上,我有复选框:

<UserControl x:Class="ZemaxWorks.UI.Views.DetectorViewer"
         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"             
         xmlns:controls="clr-namespace:ZemaxWorks.UI.Controls"/>
...
        <StackPanel Grid.Column="1" Grid.Row="1" HorizontalAlignment="Right" Orientation="Horizontal">
        <CheckBox x:Name="Scales" Style="{StaticResource CheckBoxBase}" Content="{x:Static res:Resource.DETECTOR_VIEWER_EQUAL_SCALES}"
                  IsChecked="{Binding ElementName=Scales, Path=EqualScales}"
                  />
    </StackPanel>
</Grid>

然后我创建一个dependensy属性并将其绑定到CheckBox的“IsChecked”属性:

public partial class DetectorViewer : UserControl
{
    public bool EqualScales
    {
        get { return (bool)GetValue(EqualScalesProperty); }
        set { SetValue(EqualScalesProperty, value); }
    }

    // Using a DependencyProperty as the backing store for EqualScales.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty EqualScalesProperty =
        DependencyProperty.Register(nameof(EqualScales), typeof(bool), typeof(DetectorViewer));

    public DetectorViewer()
    {
        InitializeComponent();
    }
}

在主窗口我有几个标签,需要用复选框显示我的用户控件。我用模板描述它:

<views:ViewBase x:Class="ZemaxWorks.UI.Views.BeamSizeShowDataDialog"
             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"/>
...
<views:DetectorViewer Grid.Row="1" DataContext="{Binding}" EqualScales="{Binding DataContext.IsAllEqualScales, Mode=TwoWay, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}"/>
...
</views:ViewBase>

在此视图的视图模型中,我创建属性:

public bool IsAllEqualScales
        {
            get
            {
                return allEqualScales;
            }
            set
            {
                SetProperty(ref allEqualScales, value);
            }
        }

但绑定不起作用。我需要使用TwoWay模式将依赖属性从用户控件绑定到BeamSizeShowDataDialog视图模型的属性。怎么需要正确地做到这一点?对不起,我的邮件中有一些错误。谢谢大家。

0 个答案:

没有答案