【问题标题】:XAML binding properties to UserControl in ContentPresenterXAML 将属性绑定到 ContentPresenter 中的 UserControl
【发布时间】:2012-09-08 01:56:18
【问题描述】:

我有一个名为 EditorView 的 UserControl,它根据其内容显示不同的“编辑器”(其他用户控件)。

这是 EditorView 只是为了测试我用 TextBlock 替换 FontEditor 的绑定:

<UserControl x:Class="TrikeEditor.UserInterface.EditorView" ...>

    <UserControl.Resources>
        <DataTemplate DataType="{x:Type te_texture:Texture}">
            <teuied:TextureEditor TextureName="{Binding Path=Name}"/>
        </DataTemplate>
        <DataTemplate DataType="{x:Type te_font:Font}">
            <!--<teuied:FontEditor/>-->
            <TextBlock Text="{Binding Path=Name}"/>
        </DataTemplate>
    </UserControl.Resources>

    <UserControl.Template>
        <ControlTemplate TargetType="{x:Type UserControl}">
            <ContentPresenter Content="{TemplateBinding Content}" x:Name="EditorPresenter"/>
        </ControlTemplate>
    </UserControl.Template>


</UserControl>

根据 EditorView.Content 选择正确的模板,在 TextBlock 的情况下,绑定按需要工作,但在 TextureEditor 的情况下,TextureName 属性不是。

这是来自 TextureEditor 的 sn-p:

public partial class TextureEditor : UserControl
{
    public static readonly DependencyProperty TextureNameProperty = DependencyProperty.Register("TextureName", typeof(string), typeof(TextureEditor));
    public string TextureName
    {
        get { return (string)GetValue(TextureNameProperty); }
        set { SetValue(TextureNameProperty, value); }
    }

    public TextureEditor()
    {
        InitializeComponent();
    }
}

自从我使用 UserControl 以来,我有什么特别需要做的吗?也许不同的命名空间是问题?

【问题讨论】:

    标签: wpf xaml user-controls datatemplate contentpresenter


    【解决方案1】:

    用户控件不应该影响它;不同之处在于您正在实现自己的依赖属性(而不是在 TextBlock 中使用现有的 Text)。您必须在依赖属性 PropertyChanged 处理程序中设置 TextureName 属性的值:

    public static readonly DependencyProperty TextureNameProperty = 
        DependencyProperty.Register("TextureName", typeof(string), typeof(TextureEditor),
    
        // on property changed delegate: (DependencyObject, DependencyPropertyChangedEventArgs)
        new PropertyMetadata((obj, args) => {
    
            // update the target property using the new value
            (obj as TextureEditor).TextureName = args.NewValue as string;
        })
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-22
      • 1970-01-01
      • 2016-04-30
      相关资源
      最近更新 更多