将文本块绑定到两个属性

Sko*_*der 12 c# silverlight xaml binding textblock

我有一个Textblock绑定到ItemsSource集合中的属性.我想在同一个文本块中显示该类的两个属性,但似乎我一次只能执行一个绑定.我目前有这个:

Text="{Binding Title}"
Run Code Online (Sandbox Code Playgroud)

但我希望我想附加另一个属性,所以从理论上讲它将是:

Text="{Binding Title - Author}" 
Run Code Online (Sandbox Code Playgroud)

输出看起来像"莎士比亚 - 罗密欧与朱丽叶".我已经尝试添加一个逗号,另一个绑定和其他东西,但它们都会导致抛出异常(例如元素TextBlock上的未知属性Text).

这两个属性都来自同一个类,因此我不需要有两个数据源.

Jas*_*raj 17

使用这个..它将完美地工作.

<TextBlock>
    <Run Text="{Binding Title}"></Run>
    <Run Text=":"></Run>
    <Run Text="{Binding Author}"></Run> 
</TextBlock>
Run Code Online (Sandbox Code Playgroud)

输出将是这样的,

OOPS:Balagurusamy


Mar*_*iec 8

不幸的是,Silverlight缺少一些可以处理这个问题的WPF.我可能会使用值转换器的路线,您可以传递包含标题和作者的类来格式化文本.

这是代码:

public class TitleAuthorConverter : IValueConverter
{

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (!(value is Book)) throw new NotSupportedException();
        Book b = value as Book;
        return b.Title + " - " + b.Author;
    }

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

public class Book
{
    public string Title { get; set; }
    public string Author { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

还有一些XAML:

<Grid x:Name="LayoutRoot" Background="White">
    <Grid.Resources>
        <local:Book Title="Some Book" Author="Some Author" x:Key="MyBook"/>
        <local:TitleAuthorConverter x:Key="Converter"/>
    </Grid.Resources>
    <TextBlock DataContext="{StaticResource MyBook}" Text="{Binding Converter={StaticResource Converter}}"/>
</Grid>
Run Code Online (Sandbox Code Playgroud)

这种方式的缺点是,如果属性发生更改(即实现INotifyPropertyChanged),则不会更新文本,因为该字段已绑定到类.

正如对问题的评论中所建议的那样,您还可以创建一个组合它们的第三个属性.这将不得不使用多绑定或值转换器.


Ada*_*ras 5

听起来你需要一个MultiBinding

<TextBlock.Text>
    <MultiBinding StringFormat="{}{0} - {1}">
        <Binding Path="Title" />
        <Binding Path="Author" />
    </MultiBinding>
</TextBlock.Text>
Run Code Online (Sandbox Code Playgroud)