将自定义用户控件的StackPanel绑定到自定义类的

时间:2016-01-26 20:04:47

标签: c# wpf binding observablecollection stackpanel

我有一个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);
    }
}

我也有自己的UserControl名为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>

代码编译并运行没有任何问题,并且在StackPanel中为ObservableCollection中的每个项创建并显示了一个Card,但是,每个Card的Title和Description都是空白的,不会获取它们各自NextBestAction的数据。

我觉得我90%都在那里。我将不胜感激任何帮助。谢谢!

UPDATE / EDIT 1:目前未调用/命中NextBestActionTypeConverter。如果我从XAML中删除ItemsControl.ItemTemplate定义,则调用NextBestActionTypeConverter,但将destinationType作为“string”。我试图强制/设置ItemsControl以了解itesm将被表示为卡片。

更新/编辑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>

1 个答案:

答案 0 :(得分:0)

我可以看到代码中存在一些潜在的问题点。

首先,您的get; set;对象中的TitleDescription定义了NextBestAction访问者方法,看起来您没有完整的属性。

如果我没记错的话,WPF的绑定系统需要具有get / set访问器的完整属性,并且不会绑定到没有它们的字段。

所以

public string title, description;

应该成为

public string Title { get; set; }
public string Description { get; set; }

另一个潜在的问题可能是你没有在Card UserControl中绑定标题/描述文本框的.Text属性。

因此,假设您没有使用基于Caliburn Micro等.Name属性自动创建Bindings的框架,此代码

<TextBlock Name="Title" ... />
<TextBlock Name="Description" ... />

应该是

<TextBlock Name="Title" Text="{Binding Title}" ... />
<TextBlock Name="Description" Text="{Binding Description}" ... />

此外,我非常确定绑定区分大小写,因此您需要确保绑定(或Name属性,如果使用Caliburn Micro)的情况与您的属性的情况相符。

最后,每当我看到UserControl硬编码.DataContext时,警告就会消失在我脑海中。 UserControls不应该这样做。他们应该从使用控件的任何代码中获取他们的DataContext,并且不应该创建他们自己的。删除在.DataContext UserControl中对Card进行硬编码的以下代码行,然后它将使用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做什么:)它通常用于将一种类型转换为另一种类型,例如将字符串"Red"更改为SolidColorBrush当您输入.Color之类的内容时,<StackPanel Background="Red" />设置为红色。我没有看到你当前的代码使用它,并建议完全摆脱它,除非你出于某些特定原因需要它。)