我們有一個我們想要由用戶控制的UI區域。基本上他們爲我們提供了一塊xaml,它定義了特定區域的外觀。將控件綁定到由域對象提供的xaml
public class Project
{
public string DisplaySpecificationXml { get; set; }
}
是否有從碰巧知道XAML,使我們可以在運行時看到它的域對象的屬性綁定一個簡單的方法;
PS - 請注意,所查看的項目將在運行時更改,然後我需要更新UI的這些區域。
我們有一個我們想要由用戶控制的UI區域。基本上他們爲我們提供了一塊xaml,它定義了特定區域的外觀。將控件綁定到由域對象提供的xaml
public class Project
{
public string DisplaySpecificationXml { get; set; }
}
是否有從碰巧知道XAML,使我們可以在運行時看到它的域對象的屬性綁定一個簡單的方法;
PS - 請注意,所查看的項目將在運行時更改,然後我需要更新UI的這些區域。
<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();
}
}
結果:
謝謝。第一遍看起來不錯。我會在今晚仔細檢查它,並在我看到它時立即接受。 – Matt
+1巧妙的轉換器使用! – JerKimball
我當然希望你信任你的用戶含蓄:有位聰明的,人們可以製作xaml與一些絕對可怕的結果... – JerKimball
這不是一個應用程序的外部消費,業務線應用程序。定義區域的用戶實際上是業務開發人員。這裏沒有很大的安全風險,但是感謝這個提示非常重要,值得讚賞。 – Matt