简体   繁体   中英

Custom style property - XAML

Is it possible to create a custom property and bind it to some value in code behind.

<Style TargetType="{x:Type TreeViewItem}" x:Key="ContainerStyle">
        <Setter Property="IsEditable" Value="{Binding IsEditable, Mode=TwoWay}" />

        <Style.Triggers>
            <Trigger Property="IsEditable" Value="True">
                <Setter Property="HeaderTemplate" Value="{StaticResource EditableTextBox}" />
            </Trigger>

        </Style.Triggers>
    </Style>

What I want to do is swap between the NotEditableText and EditableText templates depending on the value of IsEditable that is set in the PersonViewModel class. But I don't really how to bind everything together.

SOLUTION

<Style TargetType="{x:Type TreeViewItem}" x:Key="ContainerStyle">
        <Setter Property="ViewModel:PersonViewModel.IsEditable" Value="{Binding IsEditable, Mode=TwoWay}" />

        <Style.Triggers>
            <Trigger Property="ViewModel:PersonViewModel.IsEditable" Value="True">
                <Setter Property="HeaderTemplate" Value="{StaticResource EditableText}" />
            </Trigger>
        </Style.Triggers>

    </Style>

If you need to just set this style via code, you can use:

 Style containerStyle = (Style)FindResource("ContainerStyle");
 this.someTreeView.Items[0].Style = containerStyle;

Yes, but your property must be DependancyProperty . Otherwise it will not respond to Binding events. Adding DependancyProperty is quite easy.

public static readonly DependencyProperty IsSpinningProperty = 
    DependencyProperty.Register(
    "IsSpinning", typeof(Boolean),
    );

public bool IsSpinning
{
    get { return (bool)GetValue(IsSpinningProperty); }
    set { SetValue(IsSpinningProperty, value); }
}

Once you create a property like this, you can use it in Style.Triggers as you described in your scenario. Your property must be present in the class that is used in your TargetType="{x:Type MyType}" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM