Binding the value of a Setter Property in WPF

前端 未结 1 1957
臣服心动
臣服心动 2021-01-17 17:40

I have spent all day looking for a way to display a default string of text on a ComboBox and the closest I managed to find that worked was an example that uses

相关标签:
1条回答
  • 2021-01-17 18:25

    Based on your posted code I'm assuming your using the Behavior from Here

    Now if you download the sample zip in the above Link, you got 5 files that give you this set of Behavior's(found in the Behavior folder).

    Edit TextBlockAdorner.cs

    In the constructor just after the line

    m_TextBlock = new TextBlock { Style = labelStyle, Text = label };
    

    add

    m_TextBlock.DataContext = adornedElement;
    

    Now in your Style setter switch your Binding to

    <Setter Property="TextBlock.Visibility"
            Value="{Binding DataContext.Visible}" />
    

    and you should be done.

    Side-Notes:

    • Do not hold System.Windows.Visibility in your VM. Keep Visibility property in the VM as a bool and when your Binding it in xaml use a BooleanToVisibilityConverter(available directly in xaml. You do not have to create one)
    • When your defining Style's get into the habit of specifying a Type="...". It not only helps identify at a glance which Style's relate to what but also saves some redundant type qualification for each of your setter properties.

    so something like

    <Setter Property="FrameworkElement.Opacity"
            Value="0.8" />
    

    will be

    <Style x:Key="watermarkLabelStyle"
            TargetType="{x:Type TextBlock}">
      ...
      <Setter Property="Opacity"
              Value="0.8" />
    
    • Finally hopefully this is just a typo in your code but if not try to follow some naming convention with your Properties. In your VM, your property is called Visible while it's private back-end is _visibile.
    0 讨论(0)
提交回复
热议问题