WPF Button Content Based on DataContext Settings

I work with a WPF and MVVM template, I have a simple view, which consists of a button that should display one or the other depending on the DataContext (viewmodel) property. I used datatriggers and datatemplates to try to do this job, but for some the reason the binding is not evaluating (or am I doing something wrong).

    <Button x:Class="EpicNavalBattle.View.PositionView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 

        >
    <Button.Resources>
        <DataTemplate x:Key="Hidden">
            <Label Content="Hidden"></Label>
        </DataTemplate>
        <DataTemplate x:Key="Shown">
            <Label Content="{Binding Path=Content.ContentName}" />
        </DataTemplate>



    </Button.Resources>
    <Button.Style>
        <Style TargetType="{x:Type Button}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding Revealed}" Value="False">
                    <Setter Property="ContentTemplate" Value="{DynamicResource Hidden}"></Setter>

                </DataTrigger>
                <DataTrigger Binding="{Binding Revealed}" Value="True">
                    <Setter Property="ContentTemplate" Value="{DynamicResource Shown}"></Setter>

                </DataTrigger>
            </Style.Triggers>
        </Style>

    </Button.Style>


</Button>

: Content ViewModel ( datacontext), Model ContentName, Model. , Content = "Binding...." , . , (, ) ( , , , ). !

+3
1

, :

ContentControls, , Button, DataContext DataTemplate. , DataContext, .

:

{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Button}}, Path=DataContext.Content.ContentName}

:

<Setter Property="Content" Value="{Binding Content.ContentName}"></Setter>

Hidden btw, :

            <Button.Style>
                <Style TargetType="{x:Type Button}">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding Revealed}" Value="True">
                                <Setter Property="Content" Value="{Binding Content.ContentName}"></Setter>
                        </DataTrigger>
                        <DataTrigger Binding="{Binding Revealed}" Value="False">
                                <Setter Property="Content" Value="Hidden"></Setter>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </Button.Style>

: :

<Style TargetType="{x:Type Button}">
    <Setter Property="Content" Value="Hidden" />
    <Style.Triggers>
        <DataTrigger Binding="{Binding Revealed}" Value="True">
            <Setter Property="Content" Value="{Binding Content.ContentName}" />
        </DataTrigger>
    </Style.Triggers>
</Style>
+4

Source: https://habr.com/ru/post/1785880/


All Articles