I'm currently learning WPF and data binding got me...Any help is appreciated.
So I have two UserControls, let's say 1 and 2, inside and are simply displayed side-by-side in MainWindow.xaml. And in UserControl2 I want to bind something to an element of UserControl1. Like the code below that's failed(Obiviously):
{Binding ElementName=FolderView, Path=SelectedValue, Mode=OneWay}
where FolderView is a TreeView
in UserControl1, and I want to get its property in UserControl2.
I'm still very new to the MVVM thing. I think a static ViewModel would have solved it (Rectify me if this is bad). But the SelectedValue
property of a TreeView
is readonly
and I don't know how to bind it to a ViewModel.
Like you said MVVM could help.
You create a view for each of your UserControls. And you create a Viewmodel for each of them. I had the same problem at first look at these 2 they helped me alot with your problem. If you need more help just comment and I can explain some more.
https://softwareengineering.stackexchange.com/questions/408890/wpf-usercontrol-reuse-with-mvvm
Forget about all that binding. Turns out that when a TreeView
's SelectedItemChanged
. The RoutedPropertyChangedEventArgs<object>
's NewValue
contains the information I needed, which is the Tag
property.
private void FolderView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
MainViewModel.TVVM.TESTBOX = ((TreeViewItem)(e.NewValue)).Tag.ToString();
}
The MainViewModel.TVVM.TESTBOX
is just a {get;set;}
and MainViewModel.TVVM
is a static (it's the only way I can think of, idk if static is good in this case) property of MainViewModel
. Just gonna put all the related codes here for future reference.
TreeViewVM.cs
public class TreeViewVM : VMBase
{
private string _testbox;
public string TESTBOX
{
get { return _testbox; }
set { _testbox = value;
OnPropertyChange(nameof(TESTBOX));}
}
}
MainViewModel.cs
public class MainViewModel
{
public static TreeViewVM TVVM { get; set; }
public MainViewModel()
{
TVVM = new TreeViewVM();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.