32

次のような UserControl を作成しました。

<UserControl>
    <StackPanel Orientation="Vertical">
        <StackPanel x:Name="Launch" Orientation="Horizontal" Visibility="Collapsed">
            <!-- Children here -->
        </StackPanel>
        <ToggleButton x:Name="ToggleLaunch" IsChecked="False" Content="Launch"/>
    </StackPanel>
</UserControl>

DataTrigger を使用して、ToggleButton がチェックされたときに「Launch」StackPanel が表示されるようにし、それ以外の場合は折りたたまれたままにしようとしました。ただし、実行時に「オブジェクトの初期化に失敗しました (ISupportInitialize.EndInit)。トリガー コレクションのメンバーは EventTrigger 型である必要があります」というエラーが表示されます。UserControl と StackPanel のトリガー コレクションに追加しようとしましたが、成功しませんでした。私のトリガー XAML は次のようになります。

<DataTrigger Binding="{Binding ElementName=ToggleLaunch, Path=IsChecked}" Value="True">
    <Setter TargetName="Launch" Property="UIElement.Visibility" Value="Visible"/>
</DataTrigger>
4

4 に答える 4

55

MSDN Docsから、Richard C. McGuire からの (少し言い換えた) 回答によると:

DataTriggers は、XML タグStyleControlTemplate、およびDataTemplateと一緒に使用できます。

たとえば、トリガーを に追加しようとすると、次のTextBlockエラーが生成されます。

エラー: Triggers コレクションのメンバーは EventTrigger 型である必要があります

なんで?Aは、またはTriggerの内部にのみ配置でき、直接内部に配置しようとしています。StyleControlTemplateDataTemplateTextBlock

この場合、修正は簡単です。トリガーを style でラップし、このスタイルを 内に配置するTextBlockと、エラーが消えます。

修正のエラー生成 XAMLは次のとおりです。

<TextBlock x:Name="Hello" Text="{Binding Hello, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
  <TextBlock.Triggers>
      <DataTrigger Binding="{Binding Hello}" Value="GoGreen">
          <Setter Property="Foreground" Value="Green" />
      </DataTrigger>
  </TextBlock.Triggers>
</TextBlock>

修正の XAML は次のとおりです。

<TextBlock x:Name="Hello" Text="{Binding Hello, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
    <TextBlock.Style>
        <Style TargetType="TextBlock">
            <Setter Property="Foreground" Value="Red" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding Hello}" Value="GoGreen">
                    <Setter Property="Foreground" Value="Green" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </TextBlock.Style>
</TextBlock>

を入力するGoGreenと、テキストが緑色になることを示すスクリーンショットの例を次に示します。

ここに画像の説明を入力

...そして何か他のものを入力すると、テキストはデフォルトで赤になります:

ここに画像の説明を入力

Web 上には、WPF トリガーに関する無料の資料がたくさんあります。それらはすべて、概念を説明するのにかなり適切な仕事をしています

于 2014-09-20T17:39:31.900 に答える
5

スタックパネルの可視性をトグルボタンの IsChecked プロパティにバインドすることもできます。カスタム ValueConverter を使用する必要があります。ここに私がオンラインで見つけたものがあります:

/// <summary>  
/// WPF/Silverlight ValueConverter : Convert boolean to XAML Visibility
/// </summary>  
[ValueConversion(typeof(bool), typeof(Visibility))]
public class VisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) =>
        value != null && (bool)value ? Visibility.Visible : Visibility.Collapsed;
 
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) =>
        (Visibility)value == Visibility.Visible;
}
于 2009-05-07T21:06:31.530 に答える