【问题标题】:Bind content presenter content to a visual element将内容演示者内容绑定到可视元素
【发布时间】:2016-12-15 22:20:34
【问题描述】:

我有一个带有项目源的项目控件,我希望它显示预览

<ItemsControl ItemsSource="{Binding Path=Children}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>                                    
            <ContentControl>
                <ContentControl.ContentTemplate>
                    <DataTemplate>
                        <ContentPresenter Content="{Binding Preview}"/>
                     </DataTemplate>
                </ContentControl.ContentTemplate>
            </ContentControl>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

预览是一个网格

public class Child
{
    public Grid Preview { get; set; }
    public Child()
    {
        Preview = new Grid();
        Preview.Children.Add(new TextBlock() { Text = "Test"});
        Preview.Background = new SolidColorBrush(Colors.Red);
    }
}    

但它似乎没有渲染任何东西,我错过了什么?

【问题讨论】:

  • 在视图模型中创建 UI 元素不是 MVVM。

标签: c# wpf mvvm data-binding


【解决方案1】:

试试这样,

 <ItemsControl ItemsSource="{Binding Children}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <ContentPresenter Content="{Binding Preview}"/>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>

<ItemsControl ItemsSource="{Binding Path=Children}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <ContentControl Content="{Binding}">
                    <ContentControl.ContentTemplate>
                        <DataTemplate>
                            <ContentPresenter Content="{Binding Preview}"/>
                        </DataTemplate>
                    </ContentControl.ContentTemplate>
                </ContentControl>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>

没有数据上下文,所以没有显示任何内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-01
    • 2016-03-05
    • 1970-01-01
    • 1970-01-01
    • 2011-05-22
    • 2013-05-04
    相关资源
    最近更新 更多