【问题标题】:WPF C# DataBinding ListWPF C# 数据绑定列表
【发布时间】:2014-06-04 22:26:49
【问题描述】:

我正在尝试使用 WPF 使用数据绑定为 Visual C# 中的列表框制作自定义样式。

我有以下课程:

public class Page
{
    public readonly DateTime Sent;
    public readonly string PagerID;
    public readonly string Message;
    public readonly string Status;

    private Page(DateTime sent, string pagerID, string message, string status)
    {
        Sent = sent;
        PagerID = pagerID;
        Message = message;
        Status = status;
    }

    public static List<Page> GetPages()
    {
        ...
    }

    public override string ToString()
    {
        return Sent + ": " + PagerID + " - " + Message;
    }
}

以及以下 WPF .xaml:

<Window x:Class="KentBox.utilities.RecentPages"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:KentBox.utilities"
        Title="RecentPages" Height="640" Width="480">

    <Window.DataContext>
        <ObjectDataProvider x:Name="Provider" ObjectType="{x:Type local:Page}" MethodName="GetRecentPages" />
    </Window.DataContext>

    <Window.Resources>
        <Style TargetType="{x:Type ListBox}">
            <Setter Property="ItemTemplate">
                <Setter.Value>
                    <DataTemplate>
                        <Border>
                            <TextBlock Text="{Binding Message}" HorizontalAlignment="Stretch"></TextBlock>
                        </Border>
                    </DataTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Window.Resources>

    <ListBox ItemsSource="{Binding}" />
</Window>

如果我将 TextBlock Text 更改为 ="{Binding}" 而不是 {Binding Message},我可以让页面显示被覆盖的 ToString() 内容。

我不知道如何使绑定只显示页面的消息部分。 Visual Studio 告诉我

无法解析“System.Windows.Data.ObjectDataProvider”类型的数据上下文中的属性“消息”

我不知道如何更改所述数据上下文的类型。有人能指出我正确的方向吗?

【问题讨论】:

  • 消息必须是公共属性。它需要有一个获取。
  • 只能绑定属性

标签: c# wpf data-binding


【解决方案1】:

消息必须是公共属性。它需要有一个获取。

public string Message { get; private set; }

【讨论】:

  • 我知道这很简单。现在可以使用了,谢谢!
猜你喜欢
  • 2010-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-29
  • 2014-08-06
  • 2011-01-17
相关资源
最近更新 更多