【发布时间】:2018-05-19 15:00:05
【问题描述】:
我不确定如何从父控件设置子控件的 viewmodel 属性。下面我试图访问 IntValue,但我收到一条错误消息,指出它在用户控件中不存在。那是因为它存在于与用户控件绑定的视图模型中。
ChildViewModel.cs
public class ChildViewModel : ViewModelBase
{
public ChildModel Model { get; private set; }
public int IntValue
{
get
{
return Model.IntValue;
}
set
{
Model.IntValue = value;
OnPropertyChanged();
}
}
public ChildViewModel()
{
Model = new ChildModel();
}
}
ParentControl.xaml
<UserControl
x:Class="EmbeddedControls.ParentControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:EmbeddedControls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006">
<Grid>
<local:ChildControl IntValue="4">
</Grid>
</UserControl>
所以我在这里要做的是在 xaml 中创建控件时更新 IntValue 内联。有没有办法做到这一点?提前致谢。
【问题讨论】:
-
闻起来就像你走错了路。阅读此答案stackoverflow.com/a/44729258/1228 并确保您没有犯同样的错误。您的 DataContext 应该在可视化树中流动,除了正确设计视图模型之外,您无需做任何事情。