Hi,@William Liu. Welcome to Microsoft Q&A.
In WPF, you could get all x:Key
in Resources through this.Resources.Keys
.
The reference code is as follows.
<Window.Resources>
<system:String x:Key="MyName">Will</system:String>
<system:String x:Key="MyAddress">Beijing</system:String>
</Window.Resources>
<StackPanel>
<TextBlock x:Name="Text1" Loaded="MyNameTb_Loaded"/>
<TextBlock x:Name="Text2" Loaded="MyAddressTb_Loaded"/>
</StackPanel>
public partial class MainWindow : Window
{
List<string> keys = new List<string>();
public MainWindow()
{
InitializeComponent();
foreach (string key in this.Resources.Keys) {
keys.Add(key);
}
}
private void MyNameTb_Loaded(object sender, RoutedEventArgs e)
{
Text1.Text = keys[0];
}
private void MyAddressTb_Loaded(object sender, RoutedEventArgs e)
{
Text2.Text = keys[1];
}
}
If you want to use key-value data types in XAML, you could try using DictionaryEntry
. Here is how to use it.
xmlns:collections="clr-namespace:System.Collections;assembly=mscorlib"
<Window.Resources>
<collections:DictionaryEntry x:Key="MyDictionaryEntry" Key=" MyName " Value=" Will "></collections:DictionaryEntry>
</Window.Resources>
<StackPanel>
<TextBlock Text="{Binding Path=Key,Source={StaticResource MyDictionaryEntry}}"></TextBlock>
<TextBlock Text="{Binding Path=Value,Source={StaticResource MyDictionaryEntry}}"></TextBlock>
</StackPanel>
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.