Question

I have UserControl called EditorView that shows different "editors" (other user controls) based on its Content.

This is EditorView just to test the binding I replaced the FontEditor with TextBlock:

<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>

The right template is getting picked based on the EditorView.Content and in the case of TextBlock the binding works as desired but in the case of TextureEditor the TextureName property isn't.

Here is snippet from the TextureEditor:

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();
    }
}

Is there anything special that I have to do since I'm using UserControl? Maybe being different namespace is the problem?

Was it helpful?

Solution

The User Control shouldn't affect it; the difference is that you're implementing your own dependency property (rather than using the existing one Text in TextBlock). You have to set the value of the TextureName property in the Dependency Property PropertyChanged handler:

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;
    })
);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top