【问题标题】:Silverlight: Bind StaticResource name to a comboboxSilverlight:将静态资源名称绑定到组合框
【发布时间】:2011-08-02 14:21:12
【问题描述】:

我有两个定义为静态资源的数据模板。现在我有一个包含每个名称的组合框。是否可以让您的控件利用这些静态资源作为项目模板来绑定到组合框中所选静态资源的名称?

提前致谢。

【问题讨论】:

    标签: silverlight data-binding


    【解决方案1】:

    这里有一些看起来很疯狂但运行良好的东西。

    <Grid x:Name="LayoutRoot">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <ComboBox x:Name="cboTemplate" DisplayMemberPath="Key" SelectedValuePath="Key" SelectedValue="Blue">
            <ComboBox.ItemsSource>
                <ResourceDictionary>
                    <DataTemplate x:Key="Blue">
                        <TextBlock Foreground="Blue" Text="{Binding}" />
                    </DataTemplate>
                    <DataTemplate x:Key="Red">
                        <TextBlock Foreground="Red" Text="{Binding}" />
                    </DataTemplate>
                </ResourceDictionary>
            </ComboBox.ItemsSource>
        </ComboBox>
        <ContentPresenter Grid.Row="1" Content="Hello World" ContentTemplate="{Binding SelectedItem.Value, ElementName=cboTemplate}" />
    </Grid>
    

    资源字典基本上是KeyValuePair&lt;object, object&gt; 的集合,但Xaml 解析提供了使用x:Key 属性填充它的优势。所以这个 ComboBox 显示了Key 属性,但它的SelectedItem 将是KeyValuePair&lt;object, object&gt;,其Value 属性是我们想要的DataTemplate。我们现在可以在 ContentTemplateItemTemplate 属性上使用元素到元素的绑定。

    如果您还需要可用作静态资源的 DataTemplate,并且希望避免代码重复,您可以将它们放在单独的资源字典 xaml 文件中。然后你可以使用:-

            <ComboBox.ItemsSource>
                <ResourceDictionary Source="DataTemplateResources.xaml" />
            </ComboBox.ItemsSource>
    

    以及将它们包含在静态资源中,例如:-

     <UserControl.Resources>
         <ResourceDictionary>
              <ResourceDictionary.MergedDictionaries>
                   <ResourceDictionary Source="DataTemplateResources.xaml" />
              </ResourceDictionary.MergedDictionaries>
              <!-- other resources here -->
         </ResourceDictionary>
     </UserControl.Resources>
    

    【讨论】:

    • 跟我想的不太一样。我有 itemtemplate 的绑定语句,我希望“PushpinTemplate”绑定到组合框中当前选定项目的值.
    • @Mortenbpost: 你的 ComboBox 不能使用资源字典作为它的 itemsource 因为 .... ?
    猜你喜欢
    • 1970-01-01
    • 2021-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多