将自定义用户控件的 StackPanel 绑定到自定义类的可观察集合
本文关键字:自定义 观察 集合 StackPanel 用户 控件 绑定 | 更新日期: 2023-09-27 18:31:56
我有一个 ObservableCollection'<'NextBestAction'>' NextBestActions 称为 NextBestActions,其中 NextBestAction 是:
[TypeConverter(typeof(NextBestActionTypeConverter))]
public class NextBestAction : IDisposable
{
public bool isDismissable, dismissed, completed;
public NextBestActionType type;
public string title, description;
public void Dispose()
{
this.Dispose();
}
public NextBestAction()
{
}
public NextBestAction(string title, string description)
{
this.title = title;
this.description = description;
}
public static NextBestAction Parse(Card card)
{
if (card == null)
{
return new NextBestAction();
}
return new NextBestAction(card.Title.Text, card.Description.Text);
}
}
我也有自己的用户控件,称为 Card,其中 Card 是:
public partial class Card : UserControl
{
public Card()
{
InitializeComponent();
this.DataContext = this;
}
public Card(string title, string description)
{
InitializeComponent();
this.DataContext = this;
this.Title.Text = title;
this.Description.Text = description;
}
public static Card Parse(NextBestAction nextBestAction)
{
if (nextBestAction == null)
{
return new Card();
}
return new Card(nextBestAction.title, nextBestAction.description);
}
}
使用下面的 XAML:
<UserControl x:Class="AdvancedTeller.Card"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:AdvancedTeller"
mc:Ignorable="d"
d:DesignWidth="300" Background="White" BorderBrush="#FF333333" VerticalContentAlignment="Top" Width="400">
<Grid Margin="10" VerticalAlignment="Top">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock Name="Title" Grid.Column="1" Grid.Row="0" FontSize="18.667" Margin="3"/>
<TextBlock Name="Description" Grid.Column="1" Grid.Row="1" VerticalAlignment="Top" TextWrapping="Wrap" Margin="3"/>
</Grid>
最后,我将NextBestAction的TypeConverter定义为
public class NextBestActionTypeConverter : TypeConverter
{
// Override CanConvertFrom to return true for Card-to-NextBestAction conversions.
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(Card))
{
return true;
}
return base.CanConvertFrom(context, sourceType);
}
// Override CanConvertTo to return true for NextBestAction-to-Card conversions.
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(Card))
{
return true;
}
return base.CanConvertTo(context, destinationType);
}
// Override ConvertFrom to convert from a Card to an instance of NextBestAction.
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
Card card = value as Card;
if (card != null)
{
try
{
return NextBestAction.Parse(card);
}
catch (Exception e)
{
throw new Exception(String.Format("Cannot convert '{0}' ({1}) because {2}", value, value.GetType(), e.Message), e);
}
}
return base.ConvertFrom(context, culture, value);
}
// Override ConvertTo to convert from an instance of NextBestAction to Card.
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
if (destinationType == null)
{
throw new ArgumentNullException("destinationType");
}
//Convert Complex to a string in a standard format.
NextBestAction nextBestAction = value as NextBestAction;
if (nextBestAction != null && this.CanConvertTo(context, destinationType) && destinationType == typeof(Card))
{
try
{
return Card.Parse(nextBestAction);
}
catch (Exception e)
{
throw new Exception(String.Format("Cannot convert '{0}' ({1}) because {2}", value, value.GetType(), e.Message), e);
}
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
我正在尝试将NextBestActions绑定到StackPanel,并强制NextBestActions在UI中表示为卡片。
到目前为止,我已经明白我至少需要这个
<StackPanel Grid.Column="1" Grid.Row="1" Grid.RowSpan="2" Margin="50" >
<ItemsControl Name="NextBestActionItems" ItemsSource="{Binding NextBestActions}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<AdvancedTeller:Card />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
代码编译和运行没有任何问题,并且为ObservableCollection中的每个项目创建一个卡片并在StackPanel中可见,但是,每个卡片的标题和描述都是空白的,不会获取其各自NextBestAction的数据。
我觉得我已经完成了90%。我将不胜感激任何帮助。谢谢!
更新/编辑 1:目前未调用/命中 NextBestActionTypeConverter。如果我从 XAML 中删除 ItemsControl.ItemTemplate 定义,则会调用 NextBestActionTypeConverter,但将 destinationType 作为"字符串"。我正在尝试强制/设置项目控件以了解它将表示为卡片。
更新/编辑 2(答案):以下是答案的片段:
// Override ConvertTo to convert from an instance of NextBestAction to Card.
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
if (destinationType == null)
{
throw new ArgumentNullException("destinationType");
}
//Convert Complex to a string in a standard format.
NextBestAction nextBestAction = value as NextBestAction;
if (nextBestAction != null && this.CanConvertTo(context, destinationType) && destinationType == typeof(Card))
{
try
{
return new Card();
}
catch (Exception e)
{
throw new Exception(String.Format("Cannot convert '{0}' ({1}) because {2}", value, value.GetType(), e.Message), e);
}
}
return base.ConvertTo(context, culture, value, destinationType);
}
和
public partial class Card : UserControl
{
public Card()
{
InitializeComponent();
}
}
和
<UserControl x:Class="AdvancedTeller.Card"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:AdvancedTeller"
mc:Ignorable="d"
d:DesignWidth="300" Background="White" BorderBrush="#FF333333" VerticalContentAlignment="Top" Width="400">
<Grid Margin="10" VerticalAlignment="Top">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock Name="Title" Grid.Column="1" Grid.Row="0" FontSize="18.667" Margin="3" Text="{Binding Title}"/>
<TextBlock Name="Description" Grid.Column="1" Grid.Row="1" VerticalAlignment="Top" TextWrapping="Wrap" Margin="3" Text="{Binding Description}"/>
</Grid>
我可以看到您的代码中存在一些潜在的问题点。
首先,看起来您没有完整的属性,具有get; set;
访问器方法,为NextBestAction
对象中的Title
和Description
定义。
如果我没记错的话,WPF 的绑定系统需要使用 get/set 访问器的完整属性,并且不会绑定到没有它们的字段。
所以
public string title, description;
应该成为
public string Title { get; set; }
public string Description { get; set; }
另一个潜在的问题可能是您没有绑定 .Card
用户控件中的标题/说明文本框的文本属性。
因此,假设您没有使用基于 .Name
属性自动创建绑定的框架,例如 Caliburn Micro,则此代码
<TextBlock Name="Title" ... />
<TextBlock Name="Description" ... />
应该是
<TextBlock Name="Title" Text="{Binding Title}" ... />
<TextBlock Name="Description" Text="{Binding Description}" ... />
另外,我很确定绑定区分大小写,因此您要确保绑定(如果使用 Caliburn Micro,则Name
属性)的大小写与您的属性的大小写匹配。
最后,每当我看到一个UserControl
硬编码它.DataContext
时,我的脑海中就会响起警钟。用户控件不应这样做。他们应该从使用该控件的任何代码中获取其 DataContext,而不应创建自己的代码。删除以下代码行,这些代码行在 Card
UserControl 中对.DataContext
进行硬编码,然后它将改用 NextBestActions
集合中的任何值。
public Card()
{
InitializeComponent();
this.DataContext = this; // Bad!
}
public Card(string title, string description)
{
InitializeComponent();
this.DataContext = this; // Bad!
this.Title.Text = title; // Should be replaced with bindings as above
this.Description.Text = description; // Should be replaced with bindings as above
}
(作为旁注,我不知道你在用那个TypeConverter:)做什么它通常用于将一种类型转换为另一种类型,例如,当您键入类似 <StackPanel Background="Red" />
的内容时,将字符串"Red"
更改为.Color
设置为 Red 的SolidColorBrush
。我认为它不适用于您当前的代码,并且建议您完全摆脱它,除非您出于某些特定原因需要它。