gpt4 book ai didi

c# - 如何设置 x :Reference Markup Extension programmatically?

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

是否可以在代码中为绑定(bind)设置 x:Reference 标记扩展?

例如:

{Binding SelectedItem, Source={x:Reference ComboList}}

所以我创建了这样的绑定(bind):

Binding b = new Binding("SelectedItem");
b.Source = //What to put here??

我之前使用的是 ElementName,但我在使用 NameScope 时遇到了一些问题,如 this question 中所述因为此绑定(bind)设置在我创建的 UserControl 内部的 ComboBox 中,显然如果我使用 ElementName 名称范围仅限于该 UserControl 而不是外部..

谢谢!

最佳答案

将我的评论转化为答案:

{x:Reference} is a XAML construct, it's not available in C# code

如果您需要 UserControl 内部的某些东西从外部获得属性,您必须在 UserControl 中将该属性创建为 DependencyProperty > 本身,然后通过 RelativeSource 将您的元素绑定(bind)到该属性:

在后面的UserControl代码中:

 public static readonly DependencyProperty SomeProperty = DependencyProperty.Register("Some", typeof (SomeValue), typeof (YourUserControl), new PropertyMetadata(default(SomeValue)));

public SomeValue Some
{
get { return (SomeValue) GetValue(SomeProperty); }
set { SetValue(SomeProperty, value); }
}

UserControl 可视化树中的某处:

<TextBox Text="{Binding Some, RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl}}"/>

关于c# - 如何设置 x :Reference Markup Extension programmatically?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15529350/

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