我们的UI区域我们希望由用户控制。基本上它们为我们提供了一个xaml,它定义了特定区域的外观。
public class Project
{
public string DisplaySpecificationXml { get; set; }
}
是否有一种简单的方法可以从知道xaml的域对象绑定属性,以便我们可以在运行时看到它;
PS - 请注意,查看的项目将在运行时更改,然后我需要更新UI的这些区域。
答案 0 :(得分:1)
<Window x:Class="MiscSamples.RuntimeXAML"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MiscSamples"
Title="RuntimeXAML" Height="300" Width="300">
<Window.Resources>
<local:stringToUIConverter x:Key="Converter"/>
</Window.Resources>
<UniformGrid Rows="1" Columns="2">
<ListBox ItemsSource="{Binding Projects}" x:Name="Lst"/>
<ContentPresenter Content="{Binding SelectedItem.DisplaySpecificationXml, ElementName=Lst, Converter={StaticResource Converter}}"/>
</UniformGrid>
</Window>
代码背后:
public partial class RuntimeXAML : Window
{
public List<Project> Projects { get; set; }
public RuntimeXAML()
{
InitializeComponent();
Projects = new List<Project>
{
new Project()
{
DisplaySpecificationXml =
"<StackPanel>" +
"<TextBlock FontWeight='Bold' Text='This is UserControl1'/>" +
"<ComboBox Text='ComboBox'/>" +
"</StackPanel>"
},
new Project()
{
}
};
DataContext = this;
}
}
转换器:
public class stringToUIConverter: IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null || (!(value is string)))
return null;
var header = "<Grid xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' " +
"xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>";
var footer = "</Grid>";
var xaml = header + (string) value + footer;
var UI = System.Windows.Markup.XamlReader.Parse(xaml) as UIElement;
return UI;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
结果: