开发者

WPF - Access the parent Control from inside a Style Setter ControlTemplate

开发者 https://www.devze.com 2023-01-30 06:15 出处:网络
When making controls non-amendable we display them as a TextBox to keep a consistent style. The problem is that a ComboBox can have any type of data so binding the Text property of the ControlTemplate

When making controls non-amendable we display them as a TextBox to keep a consistent style. The problem is that a ComboBox can have any type of data so binding the Text property of the ControlTemplate TextBox is not as simple as using SelectedItem.

<Style TargetType="{x:Type ComboBox}">
        <Style.Triggers>
            <Trigger Property="IsReadOnly" Value="True">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate>
                            <TextBox Text="{Binding RelativeSource={RelativeSource AncestorType={x:Type ComboBox}}, Path=????, Converter={StaticResource ResourceKey=ComboToTextConverter}, UpdateSourceTrigger=PropertyChanged}" />
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Trigger>
        </Style.Trigg开发者_运维百科ers>
    </Style>

The idea I have is to use a Converter and send the whole ComboBox so it can be handled by the Converter code. Is there anyway to do this?

Any other suggestions are welcome!


you need to use the SelectedValue and SelectedValuePath properties:

<Style TargetType="ComboBox" x:Key="cStyle">
<Style.Triggers>
  <Trigger Property="IsReadOnly" Value="True">
    <Setter Property="Template">
      <Setter.Value>
        <ControlTemplate TargetType="ComboBox">
          <TextBox Text="{Binding RelativeSource=
                   {RelativeSource TemplatedParent}, 
                   Path=SelectedValue}" />
        </ControlTemplate>
      </Setter.Value>
    </Setter>
  </Trigger>
</Style.Triggers>

and heres your ComboBox

<ComboBox Name="cbox" ItemsSource="{Binding}" 
        Style="{StaticResource cStyle}" 
        SelectedValuePath="SomeText" 
        DisplayMemberPath="SomeText" />

now when you set the IsReadOnly property to true on the ComboBox, it turns into a TextBox with the selected value as its text.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号