如何设置在后台代码中声明的依赖属性

问题描述 投票:0回答:2

我正在尝试将ViewModel类的值绑定到Window类背后的代码中声明的自定义属性。我在此示例中得到的是“成员'FullScreen'无法识别或无法访问。”错误。

这里是MainWindow类:

public partial class MainWindow : Window
    {
        public static readonly DependencyProperty FullScreenProperty =
            DependencyProperty.Register(nameof(FullScreen), typeof(bool),
                typeof(MainWindow), new PropertyMetadata(default(bool), PropertyChangedCallback));

        public bool FullScreen
        {
            get => (bool)GetValue(FullScreenProperty);
            set => SetValue(FullScreenProperty, value);
        }

        private static void PropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var value = (bool)e.NewValue;
            //this.GoToFullScreen(value);
        }

        public MainWindow()
        {
            InitializeComponent();
        }
    }

和XAML部分:

<Window x:Class="WindowDependencyPropertyTest.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:WindowDependencyPropertyTest"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800" FullScreen="{Binding FullScreenFromVm}" >
    <Grid>

    </Grid>
</Window>

实现此功能的最佳方法是什么?

c# wpf mvvm
2个回答
1
投票

假设MainWindow的DataContext设置为具有FullScreenFromVm属性的对象,这应该可以工作:

<Window x:Class="WindowDependencyPropertyTest.MainWindow" ...>
    <Window.Style>
        <Style>
            <Setter Property="local:MainWindow.FullScreen"
                    Value="{Binding FullScreenFromVm}"/>
        </Style>
    </Window.Style>
    ...
</Window>

或者您将属性绑定到MainWindow构造函数中:

public MainWindow()
{
    InitializeComponent();
    SetBinding(FullScreenProperty, new Binding("FullScreenFromVm"));
}

1
投票

您可以创建一个自定义窗口并向其添加依赖项属性

public class CustomWindow : Window
{
    // propdp FullScreenFromVm ...
}

然后您只需要更改

<Window ... >

to

<local:CustomWindow ... FullScreen="{Binding FullScreenFromVm}">

并更改窗口的基类

public partial class MainWindow : CustomWindow
{
   ...
}

这种依赖性属性在xaml中可用。


起初我以为您可以编写<local:MainWindow ...>来访问已定义的依赖项属性,但不幸的是,这会中断代码生成,因为x:Class希望包含的类型为base类。

© www.soinside.com 2019 - 2024. All rights reserved.