从样式模板绑定

时间:2018-01-30 12:27:46

标签: wpf data-binding

这是我想要完成的 - 我有一个Item控件,其item source设置为ObservableCollection此集合中的每个项目都用作viewModel,以在ItemControl中创建不同的按钮。我想知道如何从按钮样式模板绑定到此viewmodel(PersonViewModel)的属性?可以说,我想使用PersonViewModel中定义的属性来控制自定义按钮中特定元素的可见性。这是一个小示例代码:

public class MainViewModel : ViewModelBase
{
    private ObservableCollection<PersonViewModel> _personViewModelList;
    public ObservableCollection<PersonViewModel> PersonViewModelList
    {
        get => _personViewModelList;
        set
        {
            _personViewModelList= value;
            OnPropertyChanged("PersonViewModelList");
        }
    }
}
public class PersonViewModel 
{
  private bool _visible;
  public bool Visible
    {
        get => _visible;
        set
        {
            _visible= value;
            OnPropertyChanged("Visible");
        }
    }
 }

这是我的物品控件:

<ItemsControl ItemsSource="{Binding PersonViewModelList}">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <WrapPanel Width="360" />
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>

        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Button 
                    Style="{StaticResource ImageButton}">                       
                </Button>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
</ItemsControl>

这是我的自定义按钮样式:

<Style x:Key="ImageButton" TargetType="Button">
            <Setter Property="ContentTemplate">
                <Setter.Value>
                    <DataTemplate>
                        <Grid>
                            <Grid.RowDefinitions>
                                <RowDefinition Height="20" />
                            </Grid.RowDefinitions>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="20" />
                                <ColumnDefinition Width="20" />
                            </Grid.ColumnDefinitions>
//Here I want to bind to "Visible" property in PersonViewModel class. Any ideas on how to accomplish it?
                            <TextBlock Visibility="{Binding...}" Grid.Row="0" Grid.Column="1"  />
                        </Grid>
                    </DataTemplate>
                </Setter.Value>
            </Setter>
    </Style>

1 个答案:

答案 0 :(得分:1)

您可以使用以下内容:

<TextBlock Visibility="{Binding DataContext.Visible, Converter={StaticResource BooleanToVisibilityConverter}, RelativeSource={RelativeSource  Mode=FindAncestor, AncestorType=Button}}" Grid.Row="0" Grid.Column="1"  />

问题是Button的ContentPresenter有DataContext = null。