【问题标题】:Silverlight ContentControl in ItemTemplateItemTemplate 中的 Silverlight ContentControl
【发布时间】:2012-01-10 07:39:15
【问题描述】:

我试图弄清楚为什么这个代码

<UserControl x:Class="TestSilverlight.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="400">

<UserControl.Resources>
    <Button x:Key="button" Content="{Binding}" />
</UserControl.Resources>

<Grid x:Name="LayoutRoot" Background="Yellow">
    <ListBox Name="listBox">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <ContentControl Content="{StaticResource button}" />
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Grid>

using System.Collections.Generic;

namespace TestSilverlight
{
    public partial class MainPage
    {
        public MainPage()
        {
            InitializeComponent();
            listBox.ItemsSource = new List<string> {"a", "b", "c"}; //without this line it works
        }
    }
}

不起作用。它抛出解析器异常(无法在 ContentControl 中设置属性 Content)。没有绑定它可以完美地工作。还好吗?

【问题讨论】:

    标签: silverlight data-binding


    【解决方案1】:

    您的逻辑似乎有问题。如果您定义了一个 Button 类型的资源 - 它会创建一个按钮实例。您不能将控件的单个实例作为多个控件的内容。

    为什么不这样做:

    <ListBox Name="listBox">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Button Content="{Binding}" />
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
    

    【讨论】:

    • 它没有任何作用。这个例子是我想做的代码的一小部分。我没有t bind button content to show that even in that case it doesnt 工作。我唯一需要的是内容在资源中(或模板标签内的其他地方)。我希望设置项目模板的一部分(不是整个模板,在这种情况下我可以使用模板选择器)。
    • 我忘了说我的问题是为什么这个代码不起作用。
    • 可能与名称范围有关。也许尝试将资源放入 app.xaml
    • 我注意到相同的代码在 wpf 应用程序中运行良好。在我看来,这是 silverlight 的错误。
    猜你喜欢
    • 2012-05-18
    • 2011-01-20
    • 1970-01-01
    • 1970-01-01
    • 2011-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多