【问题标题】:Binding in ItemTemplate in ResourceDictionary在 ResourceDictionary 中的 ItemTemplate 中绑定
【发布时间】:2012-04-11 19:35:46
【问题描述】:

我正在开发一个 C++ Metro 风格的应用程序,但在 ListView 的 ItemTemplate(或其项目)内的绑定存在问题。如果我在我的 Page.xaml 中做对了,它就可以工作。 (简化的)代码将是:

<ListView x:Name="m_listParts" ItemsSource="{Binding PartsList}>
    <ListView.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal" Width="60" Height="60">
                <Grid>
                    <TextBlock Text="{Binding Part}"/>
                </Grid>                      
            </StackPanel>
        </DataTemplate>
    </ListView.ItemTemplate>
   <ListView.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel Orientation="Horizontal"/>
            </ItemsPanelTemplate>
   </ListView.ItemsPanel>
</ListView>

但是,我想在我的 resourceDictionary 中有 ItemTemplate 定义。但我无法弄清楚如何让绑定工作。它似乎不再找到绑定的属性。

这是我的(简化的)尝试(因为 ItemsPanel 正在工作,我想我正确加载了字典本身):

<Style x:Key="PartsListListView" TargetType="ListView">
    <Setter Property="ItemsPanel">
        <Setter.Value>
            <ItemsPanelTemplate>
                <StackPanel Orientation="Horizontal"/>
            </ItemsPanelTemplate>
        </Setter.Value>
    </Setter>
    <Setter Property="ItemTemplate">
        <Setter.Value>
            <DataTemplate>
                <StackPanel Orientation="Horizontal" Width="60" Height="60">
                    <Grid>
                        <TextBlock Text="{Binding Part}"/>
                    </Grid>                       
                </StackPanel>
            </DataTemplate>
        </Setter.Value>
    </Setter>     
</Style>

PartsList 是一个可观察的向量,它包含由 Part 属性组成的 PartViewItem 对象。

【问题讨论】:

    标签: xaml binding datatemplate microsoft-metro resourcedictionary


    【解决方案1】:

    你应该把你的 Xaml 写成

    <ListView 
        ItemsPanel="{StaticResource MyItemsPanel}" 
        ItemTemplate="{StaticResource MyItemTemplate}" .../>
    

    你有资源的地方

    <UserControl.Resources>
      <DataTemplate x:Key="MyItemTemplate" DataType="{x:Type MyItemType}">
         <StackPanel ....
      </DataTemplate>
    
      <ItemsPanelTemplate x:Key="MyItemsPanel">
         <StackPanel...
      </ItemsPanelTemplate>
    </UserControl.Resources>
    

    【讨论】:

    • 我并不完全了解如何放置这些模板。所以谢谢!
    猜你喜欢
    • 2021-12-13
    • 2013-01-31
    • 2013-02-01
    • 2012-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-05
    相关资源
    最近更新 更多