【问题标题】:How to bind ItemsControl's ItemsSource to a Property that is inside of class T from IEnumerable<T>?如何将 ItemsControl 的 ItemsSource 绑定到来自 IEnumerable<T> 的类 T 内的属性?
【发布时间】:2016-02-26 03:56:40
【问题描述】:

标题说明了一切,但可以说我有一个接口 IPersonIPerson 具有 UserControl 作为其属性。

在主 xaml 中,我已经有一个 IPerson 类型的 Observable 集合 People,并且我已将 ItemsSource 与 People ItemsSource={Binding People} 绑定

如何在 ItemsControl 中显示与 IPerson 关联的 UserControl?

界面

public interface IPerson
{
    string DisplayName { get; }

    /// <summary>
    /// Call that is going to add the UI component to XML Editor
    /// </summary>
    UserControl DisplayingUserControl { get; }
}

在虚拟机中

public ObservableCollection<IPerson> People

正在观看

    <ItemsControl ItemsSource="{Binding People}" Padding="3">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <XXX Content="{Binding DisplayingUserControl}" Height="Auto" Width="Auto"/>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>

我想知道怎么填写XXX

【问题讨论】:

  • 你想在你的主窗口中绑定用户控件吗?
  • 没有。 MainWindow(技术上是 MainWindowViewModel 但是)有ObservableCollection&lt;IPerson&gt;
  • 在您用于绑定的属性中,使用 ObservableCollection 但请注意,对于数据网格,您必须将自动生成列设置为 YES,因为在运行时才知道列类型和名称。

标签: c# wpf xaml itemscontrol itemssource


【解决方案1】:

假设您在 IPerson 界面中有一个属性 UC,您可以像这样显示 UserControl:

    <ItemsControl x:Name="IC">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Label Content="{Binding UC}" Height="Auto" Width="Auto"/>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>

【讨论】:

  • 非常感谢您的建议,但不幸的是,我无法显示任何内容...
  • 当我调试时,我看到 UC 为空,即使我正在初始化它......嗯
  • 有趣的是……为什么Label可以有一个不是标签或字符串的内容……?
  • @publicst119 名称有点混乱。其实在这里你也可以尝试各种其他的容器控件。
  • 只要控件继承了ContentControl就可以替换吧。很高兴知道。再次感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-29
  • 2014-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-16
相关资源
最近更新 更多