开发者

Can I retrieve the User Control from a TreeViewItem?

I have a TreeView bound to data (MVVM model) where I am using a user control for the data display.

        <HierarchicalDataTemplate
          DataType="{x:Type vm:SiteViewModel}" 
          ItemsSource="{Binding Children}">
          <StackPanel Orientation="Horizontal">
             <uc:MyUserControl x:Name="control1" Text="{Binding SiteName}" />
          </StackPanel>
        </HierarchicalDataTemplate>

When the item is selected, I need access to the user control itself.

I found an example of doing something similar to what I want but it used the TreeViewItem.Header. In my code, because of the binding, the TreeViewItem.Header is the SiteViewModel object.

Is there an easy way of retrieving the actual user control (of type MyUserControl) from the TreeVie开发者_StackOverflow社区wItem itself?

Thanks.


As I understand, you should specify Command, which will retrive or change some parameter. in your xaml, it will Binding on the property you want to change, may be with converter or without it. Such way is MVVM like. If you want to change Visibility between two controls, as in your case is TextBox and TextBlock, you should to create a Visibility variable in your View-Model which will represent its visibility, and bind it value to TextBox or to TextBlok. your xaml will contain following lines:

<Window.Resources>
    <local:ReverseVisibilityConverter  />
</Window.Resources>
 ....
<TextBox Name="MyTB" Visibility="{Binding tbVisibility}" />
<TextBlock Visibility="{Binding ElementName=MyTB, Path=Visibility, Converter={StaticResources ReverseVisibilityConverter }}" />




public sealed class ReverseVisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        try
        {
            var flag = (Visibility)value;
            if (flag == Visibility.Visible)
                return Visibility.Collapsed;
            else
                return Visibility.Visible;
        }
        catch
        {
            return Visibility.Visible;
        }
    }
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        try
        {
            if (((Visibility)value) == Visibility.Visible)
                return Visibility.Collapsed;
            else
                return Visibility.Visible;
        }
        catch
        {
            return Visibility.Visible;
        }
    }
}

where local is the namespace where your Converter defined and. You have denote, that tbVisibility - is the variable, which exist in Ancestor DataContext. Give me more info to help you, if it is not clear.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜