【发布时间】:2019-11-27 06:46:23
【问题描述】:
我编写了新的 WPF MVVM 应用程序。 我是 WPF 的新手。 我在将值从 MainPageModelView 绑定到 StageControl 时遇到问题。 StageControl 在 MainPage 中。 我知道如何将值绑定到 MainPage 中的元素,但我不能以同样的方式将值绑定到 StageControl。 如何将值从 MainPageModelView 绑定到 StageControl? 代码:
MainPage.xaml
<my:StageControl x:Name="stageControl1" StageIsActive="true" StageName="{Binding Stage.Name}" Grid.Row="0" Grid.Column="0"/>
...
<Label x:Name="lbTest" Content="{Binding Test}" HorizontalAlignment="Left" Margin="104,10,0,0" VerticalAlignment="Top" Height="56" Width="68"/>
StageControl.xaml.cs
public partial class StageControl : UserControl
{
string stageName;
bool stageIsActive;
public StageControl()
{
InitializeComponent();
}
public bool StageIsActive
{
get { return this.stageIsActive; }
set { this.stageIsActive = SetStageControlStatus(value); }
}
public string StageName
{
get { return this.stageName; }
set { this.stageName = SetStageName(value); }
}
private bool SetStageControlStatus(bool value)
{
if (value)
{
this.outRing.Visibility = Visibility.Visible;
return true;
}
else
{
this.outRing.Visibility = Visibility.Hidden;
return false;
}
}
private string SetStageName(string value)
{
this.text.Text = value;
return this.text.Text;
}
}
MainPageViewModel.cs
class MainPageViewModel
{
public List<Stage> Stages = new List<Stage>();
public Stage stage = new Stage(0, "Test", true);
public MainPageViewModel()
{
Stages = Stage.GetStages();
}
public string Test
{
get { return "Testowy Label"; }
set { }
}
}
编辑: MainPage.xaml.css
public MainPage()
{
InitializeComponent();
MainPageViewModel viewModel = new MainPageViewModel();
this.DataContext = viewModel;
}
【问题讨论】:
-
StageName必须是依赖属性 -
UserControl 如果使用正确,将继承 DataContext 并可以访问底层数据。还有
Page不继承DataContext!!!将 ContentControl 或 ItemsControl 与DataTemplate一起使用以保留继承。查看需要实施 INotifyPropertyChanged 以获取更改。 -
您只能为依赖属性设置绑定,而 StageName 不能。
-
我添加了依赖属性(public static readonly DependencyProperty StageNameProperty = DependencyProperty.Register("StageName", typeof(string), typeof(StageControl));)现在 StageControl 有我设置为默认值的文本/ StageControl.xaml 中的模板
标签: c# .net wpf mvvm data-binding