[英]Binding value from parent Page ViewModel to UserControl
I write new WPF MVVM app. 我编写新的WPF MVVM应用程序。 I new in WPF.
我是WPF的新手。 I have problem with binding value to StageControl from MainPageModelView.
我从MainPageModelView将值绑定到StageControl时遇到问题。 StageControl is in MainPage.
StageControl在MainPage中。 I know how binding value to element in MainPage, but I can't binding value to StageControl in this same way.
我知道如何将值绑定到MainPage中的元素,但是无法以相同的方式将值绑定到StageControl。 How can I binding value from MainPageModelView to StageControl?
如何将值从MainPageModelView绑定到StageControl? Code:
码:
MainPage.xaml 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 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 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 { }
}
}
Edit: MainPage.xaml.css 编辑: MainPage.xaml.css
public MainPage()
{
InitializeComponent();
MainPageViewModel viewModel = new MainPageViewModel();
this.DataContext = viewModel;
}
I solved the problem. 我解决了问题。 First I add dependency property to StageControl.xaml.cs, then I add binding to StageControl.xaml
首先,我将依赖性属性添加到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"/>
public Stage Stage {get;set;} = new Stage(0,"Test",true);
你需要做财产而不是公共变量
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.