【问题标题】:Binding one ElementUI in XAML to 2 source将 XAML 中的一个 ElementUI 绑定到 2 个源
【发布时间】:2013-06-30 13:48:02
【问题描述】:
  <ListBox>
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Textblock Text={Binding Path=Content} Foreground={Binding Path=TextColor}/>
            </DataTemplate>
        <ListBox.ItemTemplate>
    </ListBox>

您好,我正在 WP8 中开发图书阅读器应用程序。我有一个段落列表,我使用 ListBox 显示。正如您在我的代码中看到的那样,每个段落内容都绑定到一个文本块。在 Paragraph 类中,我定义了一个名为 TextColor 的字段来将文本块的前景色绑定到它。现在,每次用户更改颜色时,我都必须遍历故事中的所有段落并更改 TextColor 的值。有没有办法将 ListboxItem 的 2 个不同属性(即前景和文本)分别绑定到不同的源>所以我只需要更改前景一次。谢谢

【问题讨论】:

    标签: wpf silverlight windows-phone-8


    【解决方案1】:

    KooKiz 解决方案非常好。但是,如果您不想包含任何属性来管理前景色或任何视觉属性,那么您可以简单地将其设置为静态资源并绑定到该资源,而不是您可以独立于模型修改它们。

    例如,您可以定义一个ForegroundResouces 类并添加您的应用需要的不同类型的前景。

    在 App.xaml 中

    <Application.Resources>
      <local:ForegroundResouces xmlns:local="clr-namespace:YOUR-NAMESPACE" x:Key="ForegroundResouces" />
    </Application.Resources>
    

    然后定义你的类

    public class ForegroundResouces {
      public static Brush TitleForeground { get; set; }
      public static Brush ContentForeground { get; set; }
      // ...
    }
    

    然后定义你的绑定

    <ListBox>
      <ListBox.ItemTemplate>
        <DataTemplate>
          <Textblock 
            Text={Binding Path=Content} 
            Foreground={Binding Path=ContentForeground, Source={StaticResource ForegroundResouces} />
        </DataTemplate>
      <ListBox.ItemTemplate>
    </ListBox>
    

    然后你可以简单地通过修改你的静态属性来改变前景

    ForegroundResources.ContentForeground = new SolidBrush(Colors.Red);
    

    您可以制作不同的主题集,但这种解决方案可能只有在您要管理多个视觉属性时才值得。

    【讨论】:

    • 如果我没记错的话,您的解决方案将不允许在页面加载后更改颜色(因为没有通知机制)。如果这是个问题,那么ForegroundResources 类应该实现INotifyPropertyChanged,并且属性不应该是静态的。
    【解决方案2】:

    有多种方法可以为您的绑定指定不同的来源。例如,您可以使用ElementName 指向您的列表框并检索其数据上下文:

    <ListBox x:Name="MyList" ItemsSource="{Binding Path=Paragraphs}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Textblock Text="{Binding Path=Content}" Foreground="{Binding Path=DataContext.TextColor, ElementName=MyList}"/>
            </DataTemplate>
        <ListBox.ItemTemplate>
    </ListBox>
    

    但在您的情况下,在父列表上设置 Foreground 属性可能更容易。它将自动应用于所有子控件:

    <ListBox x:Name="MyList" ItemsSource="{Binding Path=Paragraphs}" Foreground="{Binding Path=TextColor}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Textblock Text="{Binding Path=Content}" />
            </DataTemplate>
        <ListBox.ItemTemplate>
    </ListBox>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-25
      • 2020-04-03
      • 1970-01-01
      • 1970-01-01
      • 2012-10-13
      • 1970-01-01
      • 2010-09-20
      • 1970-01-01
      相关资源
      最近更新 更多