首先让我们创建一个 AttachedProperty,以便可以将加载的 xaml 添加到我们想要的任何 Panel 或 ContentControl。
public class MyFrameworkObject : DependencyObject
{
public static readonly DependencyProperty RuntimeFrameWorkElementProperty = DependencyProperty.RegisterAttached("RuntimeFrameWorkElement", typeof(FrameworkElement), typeof(MyFrameworkObject),new PropertyMetadata(new PropertyChangedCallback(OnPropertyChanged)));
static void OnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
SetRuntimeFrameWorkElement(d as UIElement, e.NewValue as FrameworkElement);
}
public static void SetRuntimeFrameWorkElement(UIElement element, FrameworkElement value)
{
if (element!=null && value != null && value.Parent == null) //The loaded Control can be added to only one Control because its Parent will be set
{
var panel = element as Panel;
if (panel != null)
{
panel.Children.Add(value);
return;
}
var contentControl = element as ContentControl;
if (contentControl != null)
contentControl.Content = value;
//TODO:ItemsControl
}
}
}
ViewModel :在 ViewModel 中允许创建和加载可以绑定到上述附加属性的属性。
public class ViewModel : INotifyPropertyChanged
{
public ViewModel()
{
LoadXaml();
}
FrameworkElement frameWorkElement;
public FrameworkElement RuntimeFrameWorkElement
{
get { return frameWorkElement; }
set { frameWorkElement = value; OnPropertyChanged("RuntimeFrameWorkElement"); }
}
public void LoadXaml()
{
FileInfo f = new FileInfo(@"F:\myxaml.txt"); //Load xaml from some external file
if (f.Exists)
using (var stream = f.OpenRead())
{
this.RuntimeFrameWorkElement = XamlReader.Load(stream) as FrameworkElement;
}
}
void OnPropertyChanged(string propName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
xaml.cs
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModel();
}
xaml 让我们使用附加属性
<Window x:Class="StackoverflowQues.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:StackoverflowQues"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<Button Content="Ok"/>
<Grid local:MyFrameworkObject.RuntimeFrameWorkElement="{Binding RuntimeFrameWorkElement}"></Grid>
</StackPanel>
同样,您可以将此附加属性绑定到任何面板,例如 Stack、Dock、Wrap、Grid
<StackPanel local:MyFrameworkObject.RuntimeFrameWorkElement="{Binding RuntimeFrameWorkElement}">
</StackPanel>
或者也可以绑定到 ContentControl 或 ItemsControl(尚未做)
输出我使用的 xaml 和你的一样
注意:如果您将此附加属性指定给两个或多个面板或控件,它将仅添加到第一个。因为这样加载的 xaml 控件的父级将被设置并且将无法添加另一个控件。