【问题标题】:XAML nested DataTemplate data-bindingXAML 嵌套 DataTemplate 数据绑定
【发布时间】:2014-03-12 10:35:43
【问题描述】:

我有一个ItemsControl,它的ItemsSource 在我的ViewModel 上设置了一个Binding 到一个ObservableCollection。我在其ItemTemplate 中使用Button 控件来显示我的数据,我在Button 中使用DataTemplate 并且没有显示Binding 数据。以下是有问题的 XAML:

<ItemsControl ItemsSource="{Binding Path=ConnectedInstruments}" HorizontalAlignment="Left">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal" />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Button Height="60" VerticalAlignment="Top">
                <Button.ContentTemplate>
                    <DataTemplate>
                        <StackPanel>
                            <TextBlock Text="{Binding Path=ModelCode}" />
                            <TextBlock Text="{Binding Path=SerialNumber}" />
                        </StackPanel>
                    </DataTemplate>
                </Button.ContentTemplate>
            </Button>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Button DataTemplate 中的 TextBlock 控件均未填充。我知道这与Binding 路径有关,但是我不知道自己做错了什么。有人可以让我走上正轨吗?

编辑

public class Instrument
{
    public string ModelCode { get; set; }
    public string SerialNumber { get; set; }
}

public class ViewModel
{
    public ObservableCollection<Instrument> ConnectedInstruments { get; set; }
}

我知道ItemsControlBindingObservableCollection 是正确的Button 控件的正确计数正在显示,只有模板数据丢失。

【问题讨论】:

  • 你能不能也展示一下你的数据结构?视图模型
  • @VidasVasiliauskas - 我已经添加了相关代码
  • 您是否在应用绑定后在运行时设置这些值?你也不需要 Path 属性只需写 Text="{Binding ModelCode}"
  • @VidasVasiliauskas - 我创建了Instrument 对象,并将它们添加到VMs 构造函数中的ObservableCollection。如果我删除 Button 控件 DataTemplate 并简单地设置 Button Content="{Binding ModelCode}" 我得到输出数据。

标签: wpf xaml data-binding mvvm binding


【解决方案1】:

您需要使用ContentTemplate 而不是像这样直接设置Button 的Content 的任何具体原因? :

<ItemsControl.ItemTemplate>
    <DataTemplate>
        <Button Height="60" VerticalAlignment="Top">
            <StackPanel>
                <TextBlock Text="{Binding Path=ModelCode}" />
                <TextBlock Text="{Binding Path=SerialNumber}" />
            </StackPanel>
        </Button>
    </DataTemplate>
</ItemsControl.ItemTemplate>

【讨论】:

    猜你喜欢
    • 2012-11-14
    • 2011-03-28
    • 2012-09-30
    • 2014-06-06
    • 2013-03-01
    • 2020-03-14
    • 1970-01-01
    • 2011-08-16
    • 1970-01-01
    相关资源
    最近更新 更多