2017-12-29 49 views
1

私のアプリケーションでは、特定のTextBlockのテキストは、RadioButtonのどちらがチェックされているかによって異なります。以下のXAMLの例である:C#WPF:DataTriggerのRadioButton IsCheckedプロパティを使用

<Window x:Class="UTScanForm.Support.Window1" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
     xmlns:local="clr-namespace:UTScanForm.Support" 
     mc:Ignorable="d" 
     Title="Window1" Height="300" Width="300"> 
    <Grid> 
     <StackPanel> 
      <RadioButton x:Name="RB1" Content="RB1"/> 
      <RadioButton x:Name="RB2" Content="RB2"/> 
      <TextBlock Text="none"> 
       <TextBlock.Style> 
        <Style TargetType="TextBlock"> 
         <Style.Triggers> 
          <DataTrigger Binding="{Binding IsChecked, ElementName=RB1}" Value="True"> 
           <Setter Property="Text" Value="RB1"/> 
          </DataTrigger> 
          <DataTrigger Binding="{Binding IsChecked, ElementName=RB2}" Value="True"> 
           <Setter Property="Text" Value="RB2"/> 
          </DataTrigger> 
         </Style.Triggers> 
        </Style> 
       </TextBlock.Style> 
      </TextBlock> 
     </StackPanel> 
    </Grid> 
</Window> 

上記のコードが示すように、2つのラジオボタン、RB1RB2があります。 RB1がチェックされている場合、テキストブロックのテキストはRB1に、そうでない場合はRB2になります。しかし、コードは機能していません。私が作ったミスや正しい解決策は何かを指摘してください。

答えて

2

dependency property value precedenceが原因です。 TextBlockのText="none"属性は、そのスタイルがオーバーライドするものを上書きします。これは機能であり、バグではありません。複数のコントロールで使用されるスタイルでデフォルトを設定し、特定のインスタンスに対してデフォルトをオーバーライドできます。

修正は簡単です:スタイル設定ツールでデフォルトの "none"テキストを設定し、他のスタイル設定ツールはそれを上書きできます。

<TextBlock> 
    <TextBlock.Style> 
     <Style TargetType="TextBlock"> 
      <Setter Property="Text" Value="none" /> 
      <Style.Triggers> 
       <DataTrigger Binding="{Binding IsChecked, ElementName=RB1}" Value="True"> 
        <Setter Property="Text" Value="RB1"/> 
       </DataTrigger> 
       <DataTrigger Binding="{Binding IsChecked, ElementName=RB2}" Value="True"> 
        <Setter Property="Text" Value="RB2"/> 
       </DataTrigger> 
      </Style.Triggers> 
     </Style> 
    </TextBlock.Style> 
</TextBlock> 

これは、DataTemplateまたはControlTemplateトリガーには適用されません。属性をオーバーライドすることができます。

関連する問題