0

我有一个动态加载的用户控件库。从那个库中,我将一个 Tabitem 插入到 TabControl 中。我可以加载标签并显示它而不会出错。但是,我似乎无法使控件上的绑定起作用。

这是我用来加载它并将其添加到 TabControl 的代码:

    Assembly moduleAssembly = Assembly.Load("ControlLib");            
    UserControl uc = (UserControl)Application.LoadComponent(new System.Uri("/ControlLib;component/UserControl1.xaml", UriKind.RelativeOrAbsolute));
    TabControl itemsTab = (TabControl)this.FindName("mainTabControl");
    TabItem newTab = new TabItem();
    newTab.Content = uc;
    newTab.Header = "Test";
    itemsTab.Items.Add(newTab);
    itemsTab.SelectedItem = newTab;

这是控件的 C# 代码:

public partial class UserControl1 : UserControl
{        
    public static readonly DependencyProperty TestStringProperty = 
        DependencyProperty.Register("TestString", typeof(string), typeof(UserControl1));

    public string TestString { get; set; }

    public UserControl1()
    {
        InitializeComponent();

        TestString = "Hello World";
    }
}

这是控件的 XAML 代码:

<UserControl x:Class="ControlLib.UserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>        
        <TextBox Height="30" Width="100" HorizontalAlignment="Left" VerticalAlignment="Bottom" Text="{Binding Path=TestString, Mode=TwoWay}" />
    </Grid>
</UserControl>

当标签显示所有内容时,我看到文本框中的空白而不是“ Hello World”

我错过了什么?

4

1 回答 1

0

您仍然会将用户控件的 DataContext 设置为类的实例。您创建该实例的方式不同,因为您将加载该 dll 运行时。但从根本上说,绑定设置保持不变。

    var assembly = Assembly.LoadFrom(@"yourdllname.dll");
    Type type = assembly.GetType("ClassLibrary1.SampleViewModel"); 
    object instanceOfMyType = Activator.CreateInstance(type);

    DataContext = instanceOfMyType;

有关基本数据绑定的工作原理,请阅读 MSDN 文档

确保在屏幕顶部选择正确的框架。

编辑

通常这被创建为一个单独的类(MVVM 模式中的 ViewModel)。

 public partial class Window3 : Window, INotifyPropertyChanged
    {
        public Window3()
        {
            InitializeComponent();

            DataContext = this;
            TestString = "Hello World.";
        }

        string _testString;
        ///<summary>Gets or sets TestString.</summary>            
        public string TestString
        {
            get { return _testString; }
            set { _testString = value; OnPropertyChanged("TestString"); }
        }



        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                var e = new PropertyChangedEventArgs(propertyName);
                PropertyChanged(this, e);
            }
        }
    }
于 2012-09-01T23:26:37.370 回答