且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用MVVM模式,如何创建“设置”控件,在其他用户控件中设置数据绑定项值?

更新时间:2023-10-11 11:39:10

您好RyanRen2018,

Hi RyanRen2018,

根据根据您的描述,您似乎想通过ListBox事件更改相关的ViewModel值,如果是这样,请参考以下代码,它将相关的ViewModel定义为类中的字段,并通过ListBox事件更改VM的属性值。

According to your description, it seems that you want to change related ViewModel's value via ListBox event, if so, please refer to the following code, which define related ViewModel as field in the class, and change VM's property's value via ListBox event.

public partial class MainWindow : Window
    {

        private AppleViewModel appVM;
        private BananaViewModel banVM;
        public MainWindow()
        {


            InitializeComponent();

            appVM = new AppleViewModel()
            {
                AppleID = "Apple001",
                Size = 10,
            };
            apple.DataContext = appVM;
             
            banVM = new BananaViewModel()
            {
                BananaID = "Banana002",
                Length = 10
            };

            banana.DataContext = banVM;
        }

        

        private void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            appVM.AppleID = this.listBox1.SelectedItem.ToString();
        }
    }

祝你好运,

张龙