【发布时间】:2021-07-08 04:46:42
【问题描述】:
我有一个带有一些属性的自定义类。
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
在UserControl 中,我向自定义类添加了一个依赖属性。
public class MyUserControl : UserControl
{
public static readonly DependencyProperty Person1Property = DependencyProperty.Register
(
nameof(Person1),
typeof(Person),
typeof(MyUserControl),
new PropertyMetadata(null, Person1Changed)
);
public Person Person1
{
get { return (Person) GetValue(Person1Property); }
set { SetValue(Person1Property, value); }
}
static void Person1Changed(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (e.NewValue != e.OldValue && d is MyUserControl)
{
var instance = d as MyUserControl;
instance.Person1 = e.NewValue as Person;
}
}
}
在 MainWindow.xaml 中我想做:
<Window x:Class="MyApplication.MainWindow"
xmlns:local="clr-namespace:MyApplication"
Title="MainWindow" Height="450" Width="800">
<local:MyUserControl
Person1.Name="{Binding SomeNameInViewModel}"
Person1.Age="{Biding SomeAgeInViewModel}"
/>
</Window>
但这不起作用:( 我只能这样做:
<Window>
<local:MyUserControl Person1="{Binding Person1InViewModel}" />
</Window>
我开始思考这是否可能。 但后来我想到了 DockPanel:
<DockPanel>
<Label DockPanel.Dock="Left" />
<Label DockPanel.Dock=Right" />
</DockPanel>
是否有通过依赖属性访问 XAML 中的类属性的解决方案?
【问题讨论】:
-
为什么在视图模式下没有 Person 属性?顺便说一句:在
Person1Changed中设置instance.Person1根本没有用 - DP 已经设置为新值。 -
这能回答你的问题吗? WPF Binding to local variable
-
感谢您的回复!我已经知道如何使用 INotificationPropertychanged 接口。我在帖子中忽略了它的所有引用,以免弄乱示例。
标签: c# wpf class xaml dependency-properties