【问题标题】:Xaml Multibinding or string concatenationXaml 多重绑定或字符串连接
【发布时间】:2014-02-03 20:34:54
【问题描述】:

我正在尝试有效地构建图像的 url。此图像是大量项目的一部分,其中每个项目仅包含图像 url 后缀。包含该集合的对象具有基本 url(见下文)。

public class MyItems
{
    public string ImageUrlBase {get;set;}
    public List<MyItem> Items {get;set;}
}

public class MyItem
{
    public string ImageUrlSuffix {get;set;}
    public string Name {get;set;}
    public string Description {get;set;}
}

现在,我在 ListBox 中显示这些项目,我需要获取 ImageUrlBaseImageUrlSuffix 的组合字符串作为 ListBoxItem 中的图像源(见下文)

<DataTemplate>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <StackPanel Grid.Row="0">
            <StackPanel Orientation="Horizontal">
                <Image Source="{Binding FullImageUrl}" />     <!-- need full url here -->
                <StackPanel MaxWidth="390">
                    <TextBlock Grid.Column="1" Text="{Binding Name}" />
                    <TextBlock Grid.Column="1" Text="{Binding Description}" />
                </StackPanel>
            </StackPanel>
        </StackPanel>
    </Grid>
</DataTemplate>

除了将属性添加到 MyItem 类并手动设置完整的 Url 之外,我对我的选择感到困惑。我正在反序列化 MyItems 对象,包括 MyItem 对象的子列表,所以我不相信自定义构造函数会起作用。遍历MyItem 对象列表似乎效率极低,但我不知道更好的方法。

有什么建议吗?

【问题讨论】:

  • 要考虑的一种方法:使用继承 DependencyObjectIValueConverter,并具有“ImageUrlBase”的依赖属性。问题是您必须担心时间问题——“ImageBaseUrl”必须在任何项目之前绑定,因为对转换器 DP 的更改不会触发项目属性的刷新。
  • 此外,您可以使用 MultiBinding,如链接的 CodeProject 示例中所示。不过,这确实带来了自己的挑战,因为 WP Silverlight 中没有 AncestorType 绑定。 codeproject.com/Articles/286171/MultiBinding-in-Silverlight-5

标签: c# xaml windows-phone-8 windows-8 winrt-xaml


【解决方案1】:

您最好的解决方案是这样做:

public class MyItems
{
       public string ImageUrlBase { get; set; }
       public List<MyItem> Items { get; set; }
}

public class MyItem
{
    public string ImageUrlSuffix { get; set; }
    public string Name {get;set;}
    public string Description { get; set; }

    public MyItems Parent { get; set; }

    public string ImageUrl
    {
        get
        {
            return Parent.ImageUrlBase + ImageUrlSuffix;
        }
    }
}

你不能简单地做多重绑定,也不能做一些转换器来获取“父”DataContext,所以你必须自己构造它。

【讨论】:

  • 这就是我害怕的。谢谢。
猜你喜欢
  • 2011-01-01
  • 2016-09-12
  • 2020-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-05
  • 2013-06-28
相关资源
最近更新 更多