开发者

TreeViewItem using User Control and binding

开发者 https://www.devze.com 2023-03-19 03:23 出处:网络
I searched the archives for help but I can\'t find anything quite specific enough for my particular issue.

I searched the archives for help but I can't find anything quite specific enough for my particular issue.

I have a TreeView using MVVM to bind data and all seems good. I want to extend the functionality such that I think using a user control for the TreeView items would be good.

Here is the XAML code for the hierarchical data template used by the TreeViewItems:

        &l开发者_Go百科t;HierarchicalDataTemplate
          DataType="{x:Type vm:SiteViewModel}" 
          ItemsSource="{Binding Children}">
          <StackPanel Orientation="Horizontal">
            <TextBlock Text="{Binding SiteName}"/>
         </StackPanel>
        </HierarchicalDataTemplate>

I want to replace the TextBlock with my user control:

        <uc:MyTextBlock InternalText="{Binding SiteName}"/>

The user control (for now) just contains another TextBlock and has a dependency property called InternalText, i.e.

  <TextBlock Text="{Binding Path=InternalText}" />

and I set the DataContext in the constructor of the user control to itself:

public MyTextBlock ()
{
  InitializeComponent();
  DataContext = this;
}

This isn't working, but if I just change the template so that it specifies static text it seems to work fine:

        <uc:MyTextBlock InternalText="Some site name"/>

So how do I get the bound data to get passed to the user control? It's probably something simple but I'm new to WPF so I've not worked it out yet.

Thanks!


In the codebehind

public class MyUserControl : UserControl
{
    #region Text
    /// <summary>
    /// The <see cref="DependencyProperty"/> for <see cref="Text"/>.
    /// </summary>
    public static readonly DependencyProperty TextProperty =
        DependencyProperty.Register(
            RunningPropertyName,
            typeof(string),
            typeof(MyUserControl ),
            new UIPropertyMetadata(null));

    /// <summary>
    /// The name of the <see cref="Text"/> <see cref="DependencyProperty"/>.
    /// </summary>
    public const string TextPropertyName = "Text";

    /// <summary>
    /// The text to display
    /// </summary>
    public string Text
    {
        get { return (string)GetValue(TextProperty ); }
        set { SetValue(TextProperty , value); }
    }
    #endregion      
}

In the xaml

<UserControl x:Class="Derp.MyUserControl" 
             x:Name="root"
             SnippingXamlForBrevity="true"

and later...

<TextBlock Text="{Binding Text, ElementName=root}" />


InternalText seems to be a not dependency property. Try to convert it into one.

0

精彩评论

暂无评论...
验证码 换一张
取 消