gpt4 book ai didi

c# - 如何设置在代码隐藏中声明的依赖属性

转载 作者:行者123 更新时间:2023-12-03 11:01:40 26 4
gpt4 key购买 nike

我正在尝试将 ViewModel 类的值绑定(bind)到在 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>

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

最佳答案

前提是 MainWindow 的 DataContext设置为具有 FullScreenFromVm 的对象属性(property),这应该工作:

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

或者您在 MainWindow 构造函数中绑定(bind)属性:
public MainWindow()
{
InitializeComponent();
SetBinding(FullScreenProperty, new Binding("FullScreenFromVm"));
}

关于c# - 如何设置在代码隐藏中声明的依赖属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59752240/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com