gpt4 book ai didi

silverlight - 在 UserControl 中绑定(bind)不起作用(模板绑定(bind)到自定义依赖属性)

转载 作者:行者123 更新时间:2023-12-01 10:58:46 26 4
gpt4 key购买 nike

我有一个用户控件,我想像这样使用它:

// MainPage.xaml
<my:MyControl Data="10" />
<!-- or -->
<my:MyControl Data="{Binding SomeData}" />

它的代码绑定(bind)是这样的:

 public partial class MyControl : UserControl
{
public MyControl() {
InitializeComponent();
}
public const string DataPropertyName = "Data";
public int Data
{
get
{
return (int)GetValue(DataProperty);
}
set
{
SetValue(DataProperty, value);
}
}

public static readonly DependencyProperty DataProperty = DependencyProperty.Register(
DataPropertyName,
typeof(int),
typeof(MyControl),
new PropertyMetadata(10);
}

它的 xaml 部分是这样的:

 <UserControl>
<!-- omitted namespaces etc. -->
<Grid x:Name="LayoutRoot">
<Button x:Name="myButton" Content="{Binding Data}">
<Button.Style>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<TextBlock Text="{TemplateBinding Content}" />
</ControlTemplate>
</Setter.Value>
</Button.Style>
</Button>
</Grid>
</UserControl>

用户控件的 xaml 部分的关键行是:

<Button x:Name="myButton" Content="{Binding Data}"> 

我想将此 Button 的 Content 属性绑定(bind)到 UserControl 的属性 (Data),同时仍保留从外部为其设置值的能力 ( <my:MyControl Data="10" /> )

问题是,当我使用绑定(bind)时 - <Button x:Name="myButton" Content="{Binding Data}"> - 它不起作用(模板绑定(bind)不选择任何值)但是,如果我手动设置值,即 - <Button x:Name="myButton" Content="12">,它会起作用

最佳答案

如果您想在 UserControl 中绑定(bind)到您“自己的”依赖属性,您需要将 x:Name 添加到您的 UserControl并将其用作绑定(bind)中的 ElementName

<UserControl x:Name="myControl">
<!-- omitted namespaces etc. -->
<Grid x:Name="LayoutRoot">
<Button x:Name="myButton"
Content="{Binding Data, ElementName=myControl}">
</Button>
</Grid>
</UserControl>

要使 Template 也有效:

您需要使用 RelativeSource TemplatedParent 系统而不是 TemplateBinding,因为您需要设置 Mode=OneWay(TemplateBinding 使用 Mode=OneTime 默认情况下出于性能原因,但在您的场景中您需要 Mode=OneWay)

<Style TargetType="Button">
<Style.Setters>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<TextBlock Text="{Binding Path=Content, Mode=OneWay,
RelativeSource={RelativeSource TemplatedParent}}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style.Setters>
</Style>

关于silverlight - 在 UserControl 中绑定(bind)不起作用(模板绑定(bind)到自定义依赖属性),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13099975/

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