簡體   English   中英

將父頁面ViewModel的值綁定到UserControl

[英]Binding value from parent Page ViewModel to UserControl

我編寫新的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;
        }

我解決了問題。 首先,我將依賴性屬性添加到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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM