我编写了新的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;
}
答案 0 :(得分:0)
我解决了这个问题。 首先,我将依赖属性添加到StageControl.xaml.cs,然后将绑定添加到StageControl.xaml
...
x:Name="Stage"
...
<TextBlock x:Name="text" TextWrapping="Wrap" Text="{Binding ElementName=Stage, Path=StageName}" TextAlignment="Center" FontSize="12" HorizontalAlignment="Center" VerticalAlignment="Center"/>
答案 1 :(得分:-1)
public Stage Stage {get;set;} = new Stage(0,"Test",true);
您需要使用属性而不是公共变量