gpt4 book ai didi

c# - DependencyProperties 未按预期在 UserControl 中触发回调

转载 作者:太空狗 更新时间:2023-10-29 23:01:00 27 4
gpt4 key购买 nike

我有一个非常简单的 DependencyProperty 示例,我已经在 UserControl 上注册,但它并没有按预期工作。

我将此属性绑定(bind)到 MainWindow 中的 DP(称为 Test),它似乎在每次更改时触发 OnPropertyChanged 事件,但 DependencyProperty 在我的作为此绑定(bind)目标的 UserControl 似乎仅在第一次更改此属性时收到通知。

这是我在代码中尝试做的事情:

我的用户控件:

public partial class UserControl1 : UserControl
{
public static readonly DependencyProperty ShowCategoriesProperty =
DependencyProperty.Register("ShowCategories", typeof(bool), typeof(UserControl1), new FrameworkPropertyMetadata(false, OnShowsCategoriesChanged));

public UserControl1()
{
InitializeComponent();
}

public bool ShowCategories
{
get
{
return (bool)GetValue(ShowCategoriesProperty);
}
set
{
SetValue(ShowCategoriesProperty, value);
}
}

private static void OnShowsCategoriesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
//this callback is only ever hit once when I expect 3 hits...

((UserControl1)d).ShowCategories = (bool)e.NewValue;
}
}

主窗口.xaml.cs

public partial class MainWindow : Window, INotifyPropertyChanged
{
public MainWindow()
{
InitializeComponent();

Test = true; //this call changes default value of our DP and OnShowsCategoriesChanged is called correctly in my UserControl

Test = false; //these following calls do nothing!! (here is where my issue is)
Test = true;
}

private bool test;
public bool Test
{
get { return test; }
set
{
test = value;
OnPropertyChanged("Test");
}
}

public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string property)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(property));
}
}
}

主窗口.xaml

<Window x:Class="Binding.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:uc="clr-namespace:Binding"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
Title="MainWindow" Height="350" Width="525">
<Grid>
<uc:UserControl1 ShowCategories="{Binding Test}" />
</Grid>
</Window>

最佳答案

问题是您正在将 ShowCategories 值设置为其自身:

((UserControl1)d).ShowCategories = (bool)e.NewValue;

这一行没有用,因为 ShowCategories 的值已经被修改了。这就是为什么您首先处于属性更改回调中的原因。乍一看,这可能被视为空操作:毕竟,您只是将属性值设置为其当前值,这在 WPF 中不会引发任何更改。

但是,由于绑定(bind)不是双向的,更改属性值会覆盖绑定(bind)。这就是为什么不再引发回调的原因。只需删除回调中的分配即可。

关于c# - DependencyProperties 未按预期在 UserControl 中触发回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12785846/

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