gpt4 book ai didi

c# - 某些属性名称的 WPF 绑定(bind)问题

转载 作者:行者123 更新时间:2023-11-30 12:35:30 24 4
gpt4 key购买 nike

我偶然发现了以下问题。我有一个复选框,其 IsChecked 属性绑定(bind)到我的 MainWindow 类中的 CLR 属性。这是源代码。

代码隐藏(MainWindow.xaml.cs):

namespace MenuItemBindingTest {
public partial class MainWindow : Window, INotifyPropertyChanged {
private bool m_backedVariable = false;
public bool IsPressAndHoldEnabled {
get { return this.m_backedVariable; }
set {
this.m_backedVariable = value;
OnPropertyChanged("IsPressAndHoldEnabled");
MessageBox.Show("Item changed: " + this.m_backedVariable);
}
}

public MainWindow() {
InitializeComponent();
this.m_checkbox.DataContext = this;
}

public event PropertyChangedEventHandler PropertyChanged;

protected void OnPropertyChanged(string propertyName) {
if (this.PropertyChanged != null) {
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}

XAML 代码(MainWindow.xaml):

<Window x:Class="MenuItemBindingTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Binding Problem Test" Width="525" Height="350">
<DockPanel>
<CheckBox x:Name="m_checkbox"
IsChecked="{Binding IsPressAndHoldEnabled}"
HorizontalAlignment="Center" VerticalAlignment="Center"
Content="Is Press and Hold enabled"/>
</DockPanel>
</Window>

现在的问题是当用户选中或取消选中复选框时,IsPressAndHoldEnabled 属性的设置访问器从未被调用(即消息框从不显示) .但是,当我将属性重命名为其他名称时它确实有效 - 例如 IsPressAndHoldEnabled2

我现在的问题是:为什么我不能使用 IsPressAndHoldEnabled 作为我的属性的名称?这与现有属性 Stylus.IsPressAndHoldEnabled 有什么关系吗?

最佳答案

很有趣。我不知道为什么,但我有解决方法:

IsPressAndHoldEnabled 属性分离到一个单独的 ViewModel 类是有效的,除非该类是从 FrameworkElement 派生的。

此外,在同一个 MainWindow 类中从常规属性更改为依赖属性也有效——DP 更改回调触发。

关于c# - 某些属性名称的 WPF 绑定(bind)问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5391905/

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