0

我们有一个希望由用户控制的 UI 区域。基本上,它们为我们提供了一段 xaml,它定义了特定区域的外观。

public class Project
{
  public string DisplaySpecificationXml { get; set; }
}

是否有一种简单的方法可以从碰巧知道 xaml 的域对象中绑定属性,以便我们可以在运行时看到它;

PS - 请注意,查看的项目将在运行时更改,然后我需要更新 UI 的这些区域。

4

1 回答 1

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();
        }
    }

结果:

在此处输入图像描述

于 2013-03-28T22:38:39.447 回答