gpt4 book ai didi

c# - ResourceDictionary WPF 样式中的交互触发器

转载 作者:可可西里 更新时间:2023-11-01 08:42:58 25 4
gpt4 key购买 nike

我有一个 ComboBox我需要在我的应用程序的几个地方使用它,所以我设置了它的大部分属性 ComboBoxResourceDictionary并将其用作我需要的样式。

ComboBox 的样式是:

<Style TargetType="{x:Type ComboBox}" x:Key="ComboBoxBranch"> 
<Setter Property="ItemsSource" Value="{Binding Branches}"></Setter>
<Setter Property="DisplayMemberPath" Value="BranchName"></Setter>
<Setter Property="SelectedItem" Value="{Binding SelectedBranch}"></Setter>
</Style>

我在我的 XAML 中像这样使用它:

<ComboBox Style="{StaticResource ComboBoxBranch}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{Binding SelectCustomerCommand}" CommandParameter="{Binding SelectedBranch}" ></i:InvokeCommandAction>
</i:EventTrigger>
</i:Interaction.Triggers>
</ComboBox>

我也想将交互触发代码移动到 ResourceDictionary ,所以我不需要在我所有的 xaml 中都写它。有可能吗?

最佳答案

据我所知,Interaction.Triggers 不能分别应用于 Style 和 ResourceDictionary。但您可以这样做,用 x:Shared="False"ComboBox 确定为资源,并为 ContentControl 引用它,如下所示:

<Window.Resources>
<ComboBox x:Key="MyComboBox"
x:Shared="False"
ItemsSource="{Binding Branches}"
DisplayMemberPath="BranchName"
SelectedItem="{Binding SelectedBranch}">

<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{Binding SelectCustomerCommand}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</ComboBox>
</Window.Resources>

<Grid>
<ContentControl Name="MyComboBox1"
Width="100"
Height="30"
HorizontalAlignment="Left"
Content="{StaticResource MyComboBox}" />

<ContentControl Name="MyComboBox2"
Width="100"
Height="30"
HorizontalAlignment="Right"
Content="{StaticResource MyComboBox}" />
</Grid>

x:Shared="True" 默认情况下,一种样式对所有样式都是通用的 - 在这种情况下,系统对重复的 Content 发誓。当 x:Shared="False" 每当它请求时为每个元素创建样式。引自 MSDN :

When set to false, modifies WPF resource-retrieval behavior so that requests for the attributed resource create a new instance for each request instead of sharing the same instance for all requests.

更多信息,请查看:

MSDN: x:Shared Attribute

编辑:替代解决方案

Here , Mr.Vspivak 发布了一个解决方案,可以让您轻松地在 Style 中设置 Interaction.Triggers

例子:

MainWindow.xaml

<Window x:Class="StylesInteractivity.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ie="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:Core="clr-namespace:Microsoft.Expression.Interactivity.Core;assembly=Microsoft.Expression.Interactions"
xmlns:int="clr-namespace:System.Windows.Interactivity"
xmlns:si="clr-namespace:StylesInteractivity"
Title="MainWindow" Height="350" Width="525">

<Window.Resources>
<si:ViewModel x:Key="Model" />
</Window.Resources>

<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>

<TextBlock Grid.Column="1" x:Name="_tblock"
Text="Default"
HorizontalAlignment="Center"
VerticalAlignment="Center"
FontSize="24"
FontWeight="Bold" />

<ListBox ItemsSource="{Binding Source={StaticResource Model}, Path=DataSource}"
Grid.Column="0"
HorizontalAlignment="Center"
VerticalAlignment="Center">

<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="FontSize" Value="24"/>
<Setter Property="FontWeight" Value="Bold"/>

<Setter Property="int:InteractivityItems.Template">
<Setter.Value>
<int:InteractivityTemplate>
<int:InteractivityItems>
<int:InteractivityItems.Behaviors>
<int:FlipOnHover />
</int:InteractivityItems.Behaviors>

<int:InteractivityItems.Triggers>
<ie:EventTrigger EventName="MouseMove">
<Core:ChangePropertyAction PropertyName="Text"
TargetObject="{Binding ElementName=_tblock}"
Value="{Binding}" />
</ie:EventTrigger>
</int:InteractivityItems.Triggers>
</int:InteractivityItems>
</int:InteractivityTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
</Grid>
</Window>

InteractivityHelper.cs

/// <summary>
/// <see cref="FrameworkTemplate"/> for InteractivityElements instance
/// <remarks>Subclassed for forward compatibility, perhaps one day <see cref="FrameworkTemplate"/> </remarks>
/// <remarks>will not be partially internal</remarks>
/// </summary>
public class InteractivityTemplate : DataTemplate
{

}

/// <summary>
/// Holder for interactivity entries
/// </summary>
public class InteractivityItems : FrameworkElement
{
private List<Behavior> _behaviors;
private List<TriggerBase> _triggers;

/// <summary>
/// Storage for triggers
/// </summary>
public List<TriggerBase> Triggers
{
get
{
if (_triggers == null)
_triggers = new List<TriggerBase>();
return _triggers;
}
}

/// <summary>
/// Storage for Behaviors
/// </summary>
public List<Behavior> Behaviors
{
get
{
if (_behaviors == null)
_behaviors = new List<Behavior>();
return _behaviors;
}
}

#region Template attached property

public static InteractivityTemplate GetTemplate(DependencyObject obj)
{
return (InteractivityTemplate)obj.GetValue(TemplateProperty);
}

public static void SetTemplate(DependencyObject obj, InteractivityTemplate value)
{
obj.SetValue(TemplateProperty, value);
}

public static readonly DependencyProperty TemplateProperty =
DependencyProperty.RegisterAttached("Template",
typeof(InteractivityTemplate),
typeof(InteractivityItems),
new PropertyMetadata(default(InteractivityTemplate), OnTemplateChanged));

private static void OnTemplateChanged(
DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
InteractivityTemplate dt = (InteractivityTemplate)e.NewValue;
#if(!SILVERLIGHT)
dt.Seal();
#endif
InteractivityItems ih = (InteractivityItems)dt.LoadContent();
BehaviorCollection bc = Interaction.GetBehaviors(d);
TriggerCollection tc = Interaction.GetTriggers(d);

foreach (Behavior behavior in ih.Behaviors)
bc.Add(behavior);

foreach (TriggerBase trigger in ih.Triggers)
tc.Add(trigger);
}

#endregion
}

FlipOnHover.cs

public class FlipOnHover : Behavior<FrameworkElement>
{
protected override void OnAttached()
{
AssociatedObject.MouseEnter += AssociatedObject_MouseEnter;
AssociatedObject.MouseLeave += AssociatedObject_MouseLeave;
Transform t = AssociatedObject.RenderTransform;

AssociatedObject.RenderTransform = new TransformGroup();
((TransformGroup)AssociatedObject.RenderTransform).Children.Add(t);
((TransformGroup)AssociatedObject.RenderTransform).Children.Add(new ScaleTransform());
base.OnAttached();
}

void AssociatedObject_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
{
((ScaleTransform)((TransformGroup)AssociatedObject.RenderTransform).Children[1]).ScaleY = 1;
}

void AssociatedObject_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
{
((ScaleTransform)((TransformGroup)AssociatedObject.RenderTransform).Children[1]).CenterX = AssociatedObject.ActualWidth / 2;
((ScaleTransform)((TransformGroup)AssociatedObject.RenderTransform).Children[1]).CenterY = AssociatedObject.ActualHeight / 2;
((ScaleTransform)((TransformGroup)AssociatedObject.RenderTransform).Children[1]).ScaleY=-1;
}

protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.MouseEnter -= AssociatedObject_MouseEnter;
AssociatedObject.MouseLeave -= AssociatedObject_MouseLeave;
}
}

ViewModel.cs

public class ViewModel
{
private ObservableCollection<String> _dataSource = new ObservableCollection<string>();

public ViewModel()
{
_dataSource.Add("Cat");
_dataSource.Add("Dog");
_dataSource.Add("Mouse");
_dataSource.Add("Owl");
_dataSource.Add("Rabbit");
}

public IEnumerable<string> DataSource
{
get { return _dataSource; }
}
}

有关详细信息,请参阅此链接:

Using Interactivity Behaviors and Actions in WPF/Silverlight Styles

关于c# - ResourceDictionary WPF 样式中的交互触发器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22321966/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com