[英]How to bind SelectionChanged Event to Visibility Property on other Element in XAML Only
給定的是一個 ComboBox 在 SelectionChanged 應該成為可見的 TextBlock 之后。 我使用 ViemModel 構建此功能。
看法:
<ComboBox SelectionChanged="{mvvmHelper:EventBinding OnSelectionChanged}" />
<TextBlock Visibility="{Binding LanguageChanged, Converter={StaticResource BooleanVisibilityConverter}}"/>
視圖模型:
bool LanguageChanged = false;
void OnSelectionChanged() => LanguageChanged = true;
我正在尋找僅在 XAML 中完成的優雅解決方案
到目前為止我嘗試了什么:
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Visibility" Value="Collapsed" />
<Style.Triggers>
<DataTrigger Binding="{Binding IsDropDownOpen, ElementName=Box, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" Value="True">
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
</Style.Triggers>
</Style>
我想我必須使用 Storyboard
<ComboBox.Style>
<Style TargetType="{x:Type ComboBox}">
<Style.Triggers>
<EventTrigger RoutedEvent="SelectionChanged">
<BeginStoryboard>
<Storyboard>
???
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Style.Triggers>
</Style>
</ComboBox.Style>
另一個選項是 System.Windows.Interactivity 但這在 WpfCore 3.1 中不可用
你有幾個不錯的選擇。
由於使用DataTrigger
的最后一個解決方案是最靈活的,因為它允許觸發ComboBox.SelectedItem
的某些狀態,我建議實施它來解決您的問題。 它也是 XAML 唯一的解決方案,不需要像LanguageChanged
這樣的額外屬性。
為了動畫像LanguageChanged
這樣的屬性,該屬性必須是DependencyProperty
。 因此,第一個示例將LanguageChanged
實現為MainWindow
的DependencyProperty
:
主窗口.xaml.cs
partial class MainWindow : Window
{
public static readonly DependencyProperty LanguageChangedProperty = DependencyProperty.Register(
"LanguageChanged",
typeof(bool),
typeof(MainWindow),
new PropertyMetadata(default(bool)));
public bool LanguageChanged
{
get => (bool) GetValue(MainWindow.LanguageChangedProperty);
set => SetValue(MainWindow.LanguageChangedProperty, value);
}
}
主窗口.xaml
<Window x:Name="Window">
<StackPanel>
<TextBlock Text="Invisible"
Visibility="{Binding RelativeSource={RelativeSource AncestorType=MainWindow}, Path=LanguageChanged, Converter={StaticResource BooleanToVisibilityConverter}}" />
<ComboBox>
<ComboBox.Triggers>
<EventTrigger RoutedEvent="ComboBox.SelectionChanged">
<BeginStoryboard>
<Storyboard>
<BooleanAnimationUsingKeyFrames Storyboard.TargetName="Window"
Storyboard.TargetProperty="LanguageChanged">
<DiscreteBooleanKeyFrame KeyTime="0" Value="True" />
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</ComboBox.Triggers>
</ComboBox>
</StackPanel>
</Window>
如果您希望切換其可見性的控件與觸發控件位於同一 scope 中,則可以直接為Visibility
設置動畫:
主窗口.xaml
<Window x:Name="Window">
<StackPanel>
<TextBlock x:Name="InvisibleTextBlock"
Text="Invisible"
Visibility="Hidden" />
<ComboBox>
<ComboBox.Triggers>
<EventTrigger RoutedEvent="ComboBox.SelectionChanged">
<BeginStoryboard>
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="InvisibleTextBlock"
Storyboard.TargetProperty="Visibility">
<DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Visible}" />
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</ComboBox.Triggers>
</ComboBox>
</StackPanel>
</Window>
如果您希望向觸發器添加更多條件,例如選擇了哪個值,您應該將TextBlock.Visibility
綁定到ComboBox.SelectedItem
並使用IValueConverter
來決定是根據當前選定的項目返回Visibility.Visible
還是Visibilty.Hidden
:
主窗口.xaml
<Window x:Name="Window">
<Window.Resources>
<!-- TODO::Implement IValueConverter -->
<SelectedItemToVisibilityConverter x:Key="SelectedItemToVisibilityConverter" />
</Window.Resources>
<StackPanel>
<TextBlock Text="Invisible"
Visibility="{Binding ElementName=LanguageSelector, Path=SelectedItem, Converter={StaticResource SelectedItemToVisibilityConverter}}" />
<ComboBox x:Name="LanguageSelector" />
</StackPanel>
</Window>
如果您希望向觸發器添加更多條件,例如選擇了哪個值,您還可以將DataTrigger
添加到TetxtBlock
,它會觸發ComboBox.SelectedItem
的一個或多個屬性。 然后,您必須將SelectedItem
強制轉換為底層ComboBox
項目的實際類型,以便在綁定路徑中引用項目的屬性。
以下示例將SelectedItem
轉換為虛構類型LanguageItem
以訪問LanguageItem.LanguageName
屬性,以觸發特定的選定語言:
主窗口.xaml
<Window x:Name="Window">
<StackPanel>
<TextBlock x:Name="InvisibleTextBlock" Text="Invisible">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Setter Property="Visibility" Value="Hidden"/>
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=LanguageSelector, Path=SelectedItem.(LanguageItem.LanguageName)}"
Value="English">
<Setter Property="Visibility" Value="Visible"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
<ComboBox x:Name="LanguageSelector" />
</StackPanel>
</Window>
我覺得@BionicCode 給出了相當全面的答案,但我會加上我的 2 美分。
我認為滿足您要求的最佳解決方案是樣式觸發器。
我看到 Bionic 包括了這一點,但這里有一個MCVE :
<Window x:Class="project-name.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="120" Width="300">
<StackPanel HorizontalAlignment="Left" VerticalAlignment="Top" Margin="15,15,0,0">
<StackPanel Orientation="Horizontal">
<TextBlock Text="Language: " VerticalAlignment="Center"/>
<ComboBox x:Name="LanguageCB" HorizontalAlignment="Left" SelectedIndex="0">
<ComboBoxItem Content="None ?"/>
<ComboBoxItem Content="English"/>
</ComboBox>
</StackPanel>
<Border Margin="0,10,0,0" BorderThickness="1" BorderBrush="Black" Padding="2">
<TextBlock Text="Becomes visible when "LanguageCB" changes selection">
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Visibility" Value="Hidden"/>
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=LanguageCB, Path=SelectedIndex}" Value="1">
<Setter Property="Visibility" Value="Visible"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</Border>
</StackPanel>
</Window>
但是......如果您真的在您的應用程序中進行本地化,而不僅僅是將此作為示例,那么我認為有一個更好的解決方案。
首先花幾分鍾閱讀WPF 全球化和本地化。
然后將至少 1 個語言資源文件添加到項目的屬性中(例如“Resources.ja-JP.resx”,並且不要忘記將 Resources.resx 文件標記為公開。將一些本地化字符串放入這些.resx 文件中。
然后將 TextBlock 的文本綁定到屬性:
<TextBlock Text="{Binding Path=ResourceName, Source={StaticResource Resources}}"/>
接下來,您需要一些代碼來處理切換文化。 這里有很多選項,但我將包含一些我過去使用過的代碼。
namespace Multi_Language_Base_App.Cultures
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Diagnostics;
using System.Windows.Data;
/// <summary>
/// Wraps up XAML access to instance of Properties.Resources,
/// list of available cultures, and method to change culture </summary>
public class CultureResources
{
private static ObjectDataProvider provider;
public static event EventHandler<EventArgs> CultureUpdateEvent;
//only fetch installed cultures once
private static bool bFoundInstalledCultures = false;
private static List<CultureInfo> pSupportedCultures = new List<CultureInfo>();
/// <summary>
/// List of available cultures, enumerated at startup
/// </summary>
public static List<CultureInfo> SupportedCultures
{
get { return pSupportedCultures; }
}
public CultureResources()
{
if (!bFoundInstalledCultures)
{
//determine which cultures are available to this application
Debug.WriteLine("Get Installed cultures:");
CultureInfo tCulture = new CultureInfo("");
foreach (string dir in Directory.GetDirectories(AppDomain.CurrentDomain.BaseDirectory))
{
try
{
//see if this directory corresponds to a valid culture name
DirectoryInfo dirinfo = new DirectoryInfo(dir);
tCulture = CultureInfo.GetCultureInfo(dirinfo.Name);
//determine if a resources dll exists in this directory that matches the executable name
string exe = System.Reflection.Assembly.GetExecutingAssembly().Location;
if (dirinfo.GetFiles(Path.GetFileNameWithoutExtension(exe) + ".resources.dll").Length > 0)
{
pSupportedCultures.Add(tCulture);
Debug.WriteLine(string.Format(" Found Culture: {0} [{1}]", tCulture.DisplayName, tCulture.Name));
}
}
catch (ArgumentException) //ignore exceptions generated for any unrelated directories in the bin folder
{
}
}
bFoundInstalledCultures = true;
}
}
/// <summary>
/// The Resources ObjectDataProvider uses this method to get
/// an instance of the _This Application Namespace_.Properties.Resources class
/// </summary>
public Properties.Resources GetResourceInstance()
{
return new Properties.Resources();
}
public static ObjectDataProvider ResourceProvider
{
get
{
if (provider == null)
provider = (ObjectDataProvider)App.Current.FindResource("Resources");
return provider;
}
}
/// <summary>
/// Change the current culture used in the application.
/// If the desired culture is available all localized elements are updated.
/// </summary>
/// <param name="culture">Culture to change to</param>
public static void ChangeCulture(CultureInfo culture)
{
// Remain on the current culture if the desired culture cannot be found
// - otherwise it would revert to the default resources set, which may or may not be desired.
if (pSupportedCultures.Contains(culture))
{
Properties.Resources.Culture = culture;
ResourceProvider.Refresh();
RaiseCultureUpdateEvent(null, new EventArgs());
Debug.WriteLine(string.Format("Culture changed to [{0}].", culture.NativeName));
}
else
{
Debug.WriteLine(string.Format("Culture [{0}] not available", culture));
}
}
private static void RaiseCultureUpdateEvent(object sender, EventArgs e)
{
EventHandler<EventArgs> handleit = CultureUpdateEvent;
CultureUpdateEvent?.Invoke(sender, e);
}
}
}
最后一塊拼圖應該是提供從 xaml 訪問文化資源的方法。 這是使用 ObjectDataProvider 完成的。
您可以將其直接放在 App.xaml 或單獨的文件中,並在 App.xaml 中引用。
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Cultures="clr-namespace:Multi_Language_Base_App.Cultures">
<!-- Contains the current instance of the ProjectName.Properties.Resources class.
Used in bindings to get localized strings and automatic updates when the culture is updated -->
<ObjectDataProvider x:Key="Resources"
ObjectType="{x:Type Cultures:CultureResources}"
MethodName="GetResourceInstance"/>
<!-- Provides access to list of currently available cultures -->
<ObjectDataProvider x:Key="CultureResourcesDS"
ObjectType="{x:Type Cultures:CultureResources}"/>
</ResourceDictionary>
當你這樣做時,你的字符串綁定可以從一開始就自動匹配系統文化(或者最終成為你的通用資源中的默認值)。 用戶也可以即時切換文化。
在您的示例中,ComboBox SelectionChanged 事件將用作更改文化的起點,如下所示:
CultureInfo CultureJapanese = new CultureInfo("ja-JP");
Cultures.CultureResources.ChangeCulture(CultureJapanese);
我更喜歡使用命令來完成這項工作,但這取決於你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.