gpt4 book ai didi

c# - 在 XAML 中为用户控件设置属性

转载 作者:太空宇宙 更新时间:2023-11-03 11:48:18 25 4
gpt4 key购买 nike

我有一个用户控件,它有一个 Integer 类型的属性,我试图在 XAML 模板中将其设置为绑定(bind)源中的一个属性。如果我使用硬编码整数设置属性,即

<MyControl MyIntegerProperty="3" />

这工作正常,但如果我尝试

<MyControl MyIntegerProperty="{Binding MyDataContextIntegerProperty}" />

它失败了。

我知道 MyDataContext 上的整数属性正在返回一个有效的整数,而且我知道这种格式有效,因为在模板的正上方,我有一行

 <TextBlock Text="{Binding MyDataContextStringProperty}" />

哪个工作正常。

是否需要在我的用户控件整数属性上设置任何标志才能使其正常工作?还是我做错了什么?

谢谢

最佳答案

MyIntegerProperty 需要是 Dependency Property可绑定(bind)...

这是一个例子:

public static readonly DependencyProperty MyIntegerProperty = 
DependencyProperty.Register("MyInteger", typeof(Integer), typeof(MyControl));

public int MyInteger
{
get { return (int)GetValue(MyIntegerProperty); }
set { SetValue(MyIntegerProperty, value); }
}

MyControl 的 XAML 定义将变为:

<MyControl MyInteger="{Binding MyDataContextIntegerProperty}" />

关于c# - 在 XAML 中为用户控件设置属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2817228/

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