[英]Is it appropriate to cast ContentPresenter.Content to 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
。
這是我能想到的最基本的例子
<Label Content="My Label" />
現在content屬性是一個不是從UIElement
派生的字符串。 因此,簡短的答案是肯定的,它不僅可能,而且很可能會發生。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.