我試圖x:TypeArguments
在我的代碼中使用,以便我可以在 XAML 中使用泛型。如何使用它的一個例子是:
<ComboBoxItem>
<local:CustomKeyValuePair x:TypeArguments="x:String, x:String"
Key="Label To Show 01"
Value="Content To Show 01" />
</ComboBoxItem>
但是,我收到了錯誤
錯誤 MC6022:只有根標記可以指定屬性“x:TypeArguments”。第 34 行位置 43。
我也嘗試xmlns:x="http://schemas.microsoft.com/netfx/2009/xaml/presentation"
在檔案頂部使用而不是http://schemas.microsoft.com/winfx/2006/xaml
,但這給了我一個不同的錯誤
錯誤 MC3072:XML 命名空間“http://schemas.microsoft.com/netfx/2009/xaml/presentation”中不存在屬性“類”。第 1 行位置 9。
有什么方法可以在 WPF 中實作這一點?
MCVE 所需代碼
自定義鍵值對.cs
namespace GenericXamlMvce;
public record CustomKeyValuePair<K, V>
{
public CustomKeyValuePair() { }
public CustomKeyValuePair(K key, V value)
{
Key = key;
Value = value;
}
public K Key { get; init; }
public V Value { get; init; }
public void Deconstruct(out K key, out V value)
{
key = Key;
value = Value;
}
}
主視窗.xaml
<Window x:Class="GenericXamlMvce.MainWindow"
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:GenericXamlMvce"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0"
Grid.Row="0"
Text="Image: "
VerticalAlignment="Center"
Margin="5 0 2 0" />
<ComboBox x:Name="DemoSelector"
Grid.Column="1"
Grid.Row="0"
SelectedIndex="0"
Margin="0 5 5 5"
DisplayMemberPath="Key"
SelectedValuePath="Value">
<ComboBoxItem>
<local:CustomKeyValuePair x:TypeArguments="x:String, x:String"
Key="Label To Show 01"
Value="Content To Show 01" />
</ComboBoxItem>
<ComboBoxItem>
<local:CustomKeyValuePair x:TypeArguments="x:String, x:String"
Key="Label To Show 02"
Value="Content To Show 02" />
</ComboBoxItem>
</ComboBox>
<TextBlock Grid.Column="0"
Grid.Row="1"
Grid.ColumnSpan="2"
Margin="10"
FontSize="20"
FontWeight="Bold"
Text="{Binding ElementName=DemoSelector, Path=SelectedValue}" />
</Grid>
</Window>
uj5u.com熱心網友回復:
有什么方法可以在 WPF 中實作這一點?
不,恐怕不會。
錯誤訊息是正確的,因為只有根元素(例如視窗)可以指定x:TypeArguments
屬性。
為了能夠CustomKeyValuePair<K, V>
在 XAML 中實體化和使用您的泛型型別,您必須為每個型別引陣列合創建它的非泛型子類,例如:
public class StringIntCustomKeyValuePair : CustomKeyValuePair<string, int> { }
XAML:
<local:StringIntCustomKeyValuePair />
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/470421.html
上一篇:從泛型結構的方法回傳閉包
下一篇:Kotlin流出泛型