我偶然发现了一个问题,并希望有人能够帮我解决问题。
我有一个带有一些UserControls的程序集。我希望在运行时从该外部程序集加载UserControl(稍后将其截屏,而不在屏幕上显示)。
UserControl xaml
<UserControl x:Class="MyAssembly.Test"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid>
<Button x:Name="TD1"
Height="30"
Width="100"
Content="{Binding ABC}"/>
</Grid>
</UserControl>
&#34;查看模型&#34;
public class TestClass : INotifyPropertyChanged
{
private string _abc = "Initial value";
public event PropertyChangedEventHandler PropertyChanged;
public string ABC
{
get
{
return _abc;
}
set
{
if (value == _abc)
{
return;
}
_abc = value;
OnPropertyChanged1("ABC");
}
}
protected virtual void OnPropertyChanged1(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
导致头痛的代码
Assembly.LoadFrom("MyAssembly.dll");
var uri = new Uri(@"/MyAssembly;component/Test.xaml"), UriKind.Relative);
var view = (Control)Application.LoadComponent(uri);
view.Width = 800;
view.Height = 600;
view.RenderSize = new Size(800, 600);
view.Background = Brushes.White;
var viewModel = new TestClass();
view.DataContext = viewModel;
viewModel.ABC = "7";
然而,在设置DataContext和改变ABC属性时,TD1内容都没有改变。它始终保持为空(如果我用调试器查看它)。
如何根据从外部程序集加载的xaml强制.Net进行绑定(在本例中为ABC)?
答案 0 :(得分:0)
好吧,我找到了make bindings的工作方式。所有人需要做的就是在视图上调用UpdateLayout
。
Assembly.LoadFrom("MyAssembly.dll");
var uri = new Uri(@"/MyAssembly;component/Test.xaml"), UriKind.Relative);
var view = (Control)Application.LoadComponent(uri);
view.Width = 800;
view.Height = 600;
view.RenderSize = new Size(800, 600);
view.Background = Brushes.White;
var viewModel = new TestClass();
view.DataContext = viewModel;
viewModel.ABC = "7";
view.UpdateLayout();