c# – DependencyProperties未按UserControl中的预期触发回调
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – DependencyProperties未按UserControl中的预期触发回调,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2400字,纯文字阅读大概需要4分钟。
内容图文
我有一个非常简单的DependencyProperty示例,我已经在UserControl上注册了,它没有按预期工作.
我将此属性绑定到MainWindow中的DP(称为Test),它似乎每次更改时触发OnPropertyChanged事件,但我的UserControl中的DependencyProperty(此绑定的目标)似乎只在第一次得到通知财产改变了.
这是我在代码中尝试做的事情:
我的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;
}
}
MainWindow.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));
}
}
}
MainWindow.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中不会引起任何更改.
但是,由于绑定不是双向的,因此更改属性值会覆盖绑定.这就是为什么不再提出回调的原因.只需删除回调中的分配即可.
内容总结
以上是互联网集市为您收集整理的c# – DependencyProperties未按UserControl中的预期触发回调全部内容,希望文章能够帮你解决c# – DependencyProperties未按UserControl中的预期触发回调所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。