【问题标题】:Bind to bound item?绑定到绑定项目?
【发布时间】:2016-07-02 05:23:07
【问题描述】:

我有 Comments 课程,我正在绑定:

<ListBox ItemsSource="{Binding CommentFiles}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock Text="{Binding Text}" TextWrapping="Wrap"/>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding UserId}"/> <!-- Here should be username -->
                    <TextBlock Text=","/>
                    <TextBlock Text="{Binding CreatedAt}"/>
                </StackPanel>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

如您所见,Comments 类具有 UserId 属性,这只是一些字符组合。我可以使用异步getUser(userID) 方法获取User 类对象。
当我绑定到 cmets 时,我想查看用户的用户名(在 User 类中)而不是 UserId。
而且我无法编辑课程。有没有办法做到这一点?

【问题讨论】:

  • 为什么不能只绑定到 UserName 而不是 UserId?
  • @Breeze 因为Comments 类没有 UserName 属性,我无法更改类。
  • cmets 类是否对用户有任何引用?如何将评论链接到用户?
  • 如何使用转换器并通过反射返回用户名?
  • 对不起,我没有看到有不同的类。但是如何在 Comments 中创建一个返回用户用户名值的属性呢?

标签: c# wpf binding windows-8.1


【解决方案1】:

您可以将 userId 与接受 userId、调用 getUser(value) 并返回用户名的值转换器结合使用。

<TextBlock Text="{Binding UserId, Converter={StaticResource MyUserIdConverter}" />

值转换器看起来像:

public class MyUserIdConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        // Add some checks here ;-)
        return GetUser((string) value);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

【讨论】:

  • 这适用于异步方法吗?因为我之前忘了说 getUser 方法是异步方法。
  • @dace return GetUser((string)name).Result;每次调用转换器时都会调用 async 方法,async 方法返回结果可能会很慢,并导致 GUI 上的显示问题。
  • 您可以使用prioritybinding显示“加载状态”,直到异步方法准备好
【解决方案2】:

基于我的评论的一个小例子。您可以加载完整的用户,也可以只加载用户名。

public class ExtendedCommentFile
{
    private readonly CommentFile _comment;

    public ExtendedComment(CommentFile comment)
    {
        _comment = comment;
    }

    public int UserId
    {
        get { return _comment.UserId; }
        set { _comment.UserId = value; }
    }

    public User User
    {
        get { return LoadTheUserHereOrInVM(); }
    }

    public string Username
    {
        get { return LoadTheUserNameHereOrInVM(); }
    }
}

/// <summary>
/// This is the unchangeable commentfile class
/// </summary>
public class CommentFile
{
    public string Text { get; set; }
    public int UserId { get; set; }
    public DateTime CreatedAt { get; set; }
}

/// <summary>
/// This is unchangeable user class
/// </summary>
public class User
{
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 2010-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多