将BooleanToVisibilityConverter绑定到TreeView HierarchicalDataTemplate中的Control

时间:2015-01-08 17:12:20

标签: c# wpf xaml mvvm treeview

我有一个绑定到DataSet的TreeView对象。在TreeView.ItemTemplate内部,我使用的是包含我正在渲染的控件的HierarchicalDataTemplate。

有没有人知道如何更改HierarchicalDataTemplate内部控件的Visibility属性?我尝试使用.NET框架中的BooleanToVisibilityConverter,但无法使绑定正常工作。

我的ViewModel中名为“ moveButtonVisibility ”的布尔变量绑定到我的XAML中按钮的Visibility属性。然后,BooleanToVisibilityConverter尝试将相应的布尔值(true / false)转换为Visibility值(可见/隐藏)。 “ moveButtonVisibility ”不是TreeView的ItemSource的一部分。

我的代码的精简版本如下所示。我已经删除了我的XAML中的所有代码,除了Button控件“MoveHereButton”我要更改可见性属性:

VIEWMODEL(C#):

private bool _moveButtonVisibility;
public bool moveButtonVisibility
{
    get { return _moveButtonVisibility; }
    set
    {
        _moveButtonVisibility = value;
        RaiseChange("moveButtonVisibility");
    }
}

查看(XAML):

<Page>
     <Page.Resources>
         <BooleanToVisibilityConverter x:Key="visibilityConverter"/>
     </Page.Resources>
     <Grid HorizontalAlignment="Center" VerticalAlignment="Top">
        <TreeView HorizontalAlignment="Center" x:Name="treeView1" VerticalAlignment="Top" ItemsSource="{Binding Path=rsParentChild}"  Background="Transparent" BorderThickness="0" BorderBrush="Transparent" >
            <TreeView.ItemContainerStyle>
               <Style>
                  <Setter Property="TreeViewItem.IsExpanded" Value="True"/>
               </Style>
            </TreeView.ItemContainerStyle>
            <TreeView.ItemTemplate>
                 <HierarchicalDataTemplate ItemsSource="{Binding Path=rsParentChild, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
                        <Grid Focusable="False" Margin="5,10,5,10">
                           <Grid.ColumnDefinitions>
                               <ColumnDefinition Width="1*"/>
                            </Grid.ColumnDefinitions>
                            <Grid.RowDefinitions>
                                <RowDefinition/>
                             </Grid.RowDefinitions>
                             <Button Name="MoveHereButton" Content="Move Here" Visibility="{Binding DataContext.moveButtonVisibility, Converter={StaticResource visibilityConverter}}" Click="MoveHereButton_Click" />
                        </Grid>
                 </HierarchicalDataTemplate>
             </TreeView.ItemTemplate>
        </TreeView>
    </Grid>
</Page>

1 个答案:

答案 0 :(得分:1)

以下工作:

<Button Name="MoveHereButton"  
        Content="Move Here" 
        Visibility="{Binding DataContext.moveButtonVisibility, 
                      RelativeSource={RelativeSource AncestorType={x:Type Page}},
                      Converter={StaticResource visibilityConverter}}" 
        Click="MoveHereButton_Click" />

关键是要添加:

RelativeSource={RelativeSource AncestorType={x:Type Page}}

Visibility绑定内部,强制控件使用DataContext的{​​{1}}。