绑定绑定项目?

时间:2016-03-16 11:05:18

标签: c# wpf binding windows-8.1

我有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属性,这只是一些字符组合。我可以使用异步User方法获取getUser(userID)类对象 当我绑定到评论时,我希望看到用户的用户名(在User类中)而不是UserId。
我无法编辑课程。有没有办法做到这一点?

2 个答案:

答案 0 :(得分:4)

您可以将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();
    }
}

答案 1 :(得分:0)

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

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
{
}