c# - 将 ContentPresenter.Content 转换为 UIElement 是否合适?

标签 c# wpf contentpresenter uielement

ContentPresenter 的内容是否会是 UIElement 以外的某个对象?鉴于该字段被声明为对象而不是 UIElement,似乎有可能存在。但是,我想不出它会在什么情况下有效,甚至它是否有效。

ContentPresenter presenter = GetTemplateChild(PART_Presenter) as ContentPresenter;
UIElement myElement = (UIElement)presenter.Content;
myElement.SomeUIMethod(); // possible InvalidOperationException?

最佳答案

我一直这样做 - 整个 MVVM 方法都是建立在非 UIElement 内容上的,这里是一个例子:

创建一个不是从 UIElement 派生的类,在本例中我将调用 MyViewModelClass。

创建一个窗口并添加这段代码

public partial class Window1 : Window
{
    public Window1()
    {
        DataContext = new MyViewModelClass();
        InitializeComponent();
    } 
}

并向 XAML 添加一些内容控件:

<Button Content="{Binding}"/>

现在您有一个 ContentPresenter(在 Button 控件模板内),其中 MyViewModelClass 作为内容。

另一个(可能更常见的)示例是 ItemControl - 让我们以一个 ListBox 为例,每个 ListBoxItem 都有一个 ContentPresenter 将列表中的内容设置为 ItemsSource

关于c# - 将 ContentPresenter.Content 转换为 UIElement 是否合适?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1824205/

相关文章:

c# - 避免绑定(bind)中的转换器

c# - 有关 WPF 及其 XAML 的一般信息

c# - 在 EventTrigger 中为 Storyboard 分配 TargetName

c# - 在 MVVM 中放置全局变量的位置(Caliburn micro)

c# - 有什么理由我不应该在彼此之上使用两个 ContentPresenters 来模拟弹出窗口?

c# - 在 C# 中将 UTC 日期时间转换为本地日期时间

c# - 迭代地将值关联到 C# 中的变量,就像 python 在 [2, 1, 3] 中为 (red, green, blue) 所做的那样

c# - MemoryCache.Default 在 .NET Core 中不可用?

c# - WPF GridViewRowPresenter 把所有内容变成Textblocks

wpf - 为什么我需要 SilverLight 中的 ContentPresenter?