[英]Can't assign user Control (view) to my ContentControl, is always null
I have a WPF application and I'm trying to display a dynamic user control in my main window.我有一个 WPF 应用程序,我试图在我的主窗口中显示一个动态用户控件。 For this I have a ContentControl and I am binding it to a property called MyFooView which is of type FooView .为此,我有一个ContentControl中,我将它绑定到一个属性叫做MyFooView其类型为FooView的。
When the constructor of my main window gets called I am assigning FooView to my UserControl as such:当我的主窗口的构造函数被调用时,我将 FooView 分配给我的 UserControl,如下所示:
//using statements above...
//public class MainWindowViewModel, implements INotifyPropertyChanged
public FooView MyFooView
{
get
{
return _myfooView;
}
set
{
if (_myfooView!= null)
{
_myfooView= value;
RaisePropertyChanged(nameof(MyFooView));
}
}
}
private FooView _myfooView;
public MainWindowViewModel()
{
MyFooView = new FooView(...); //takes in parameters
//at this point MyFooView is (null)
}
My Xaml:我的 Xml:
<Grid Grid.Row="1" Margin="30,0" Width="880">
<ContentControl Content="{Binding MyFooView}"/>
<Rectangle Stroke="Black" StrokeThickness="2"/>
</Grid>
No matter what MyFooView is always null.无论什么 MyFooView 始终为空。 Thus, the space where I'm expecting to see my view is empty.因此,我期望看到我的视图的空间是空的。 Can anyone help me understand what am I doing wrong?谁能帮我理解我做错了什么? Many thanks in advance!提前谢谢了!
It is always null because you have a null check inside the setter.它始终为空,因为您在 setter 中进行了空检查。 You can not assign a value to the property when the field is null, but the field starts off null.当该字段为空时,您不能为该属性赋值,但该字段从空开始。
Change from:更改自:
public FooView MyFooView
{
get
{
return _myfooView;
}
set
{
if (_myfooView!= null)
{
_myfooView= value;
RaisePropertyChanged(nameof(MyFooView));
}
}
}
to:到:
public FooView MyFooView
{
get
{
return _myfooView;
}
set
{
_myfooView= value;
RaisePropertyChanged(nameof(MyFooView));
}
}
Alternatively, you could perform a null check on the value
, which is perhaps what you intended to do to begin with, as such:或者,您可以对value
执行空检查,这可能是您开始时打算做的,例如:
public FooView MyFooView
{
get
{
return _myfooView;
}
set
{
if (value!= null)
{
_myfooView= value;
RaisePropertyChanged(nameof(MyFooView));
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.