Expose Parent's DataContext to children through Resource - c#

I have a situation where the parent DataContext is different from the child DataContext, and I would like to access the parent DataContext from a binding in the child. This can be done using a verbose RelativeSource like so:
<Button Content="{Binding RelativeSource={RelativeSource AncestorType={x:Type local:MainWindow}}, Path=DataContext.Bar}"/>
I would like to find a way to reference the parent's DataContext in a much more concise way. Is there a way, for example, the parent could expose a reference to it's DataContext (or any of it's properties for that matter) through a Resource defined in the parent? Ideally, the child's binding would then look something like the following (forgive me for using StaticResource as an example).
<Button Path=Bar, Content="{StaticResource parentDataContextReference}"/>
Ideally, avoiding code-behind, but open to that solution. A contrived example:
MainWindow.xaml
<Window x:Class="BindingTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:BindingTest"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<x:ArrayExtension x:Key="children" Type="{x:Type local:ChildViewModel}">
<local:ChildViewModel Name="Child 1"/>
<local:ChildViewModel Name="Child 2"/>
</x:ArrayExtension>
</Window.Resources>
<StackPanel>
<Button Content="{Binding Foo}" Height="20" Width="60"></Button>
<ListView ItemsSource="{StaticResource children}">
<ListView.ItemTemplate>
<DataTemplate>
<local:ChildView/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackPanel>
</Window>
MainWindow.xaml.cs
namespace BindingTest
{
public class MainViewModel
{
public string Foo { get; set; }
public string Bar { get; set; }
public MainViewModel()
{
Foo = "Foo";
Bar = "Bar";
}
}
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new MainViewModel();
}
}
}
ChildView.xaml
<UserControl x:Class="BindingTest.ChildView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:BindingTest"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<StackPanel Orientation="Horizontal">
<Button Content="{Binding Name}"/>
<Button Content="{Binding RelativeSource={RelativeSource AncestorType={x:Type local:MainWindow}}, Path=DataContext.Bar}"/>
</StackPanel>
</UserControl>
ChildView.xaml.cs
namespace BindingTest
{
public class ChildViewModel
{
public string Name { get; set; }
public ChildViewModel()
{
Name = "Undefined";
}
}
public partial class ChildView : UserControl
{
public ChildView()
{
InitializeComponent();
}
}
}

to long for a comment... i use RelativeSource Binding too. but i use it with "Marker Interfaces". this means simply empty interfaces which i'm putting on the Views/UserControls.
public interface IMainWindowMarker {}
public Window MainWindow : IMainWindowMarker {}
the binding the looks much the same to yours but its more readable to me.
<Button Content="{Binding RelativeSource={RelativeSource AncestorType={x:Type local:IMainWindowMarker}}, Path=DataContext.Bar}"/>

Related

Adding objects to WPF Panel displaying buttons

I want to add objects dynamicly to a ObservationCollection, which then should add buttons with a Content (value) of a field of the object to a panel.
App.xaml.cs
using System.Windows;
namespace WpfApp1
{
public partial class App : Application
{
}
}
MainWindow.xaml
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ItemsControl Name="dashboardList">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Content="{Binding Name}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</Window>
DashboadViewModel.cs
using System.Collections.ObjectModel;
namespace WpfApp1
{
public class DashboardViewModel
{
public ObservableCollection<Dashboard> Dashboards { get; set; }
public DashboardViewModel()
{
LoadDashboards();
}
public void LoadDashboards()
{
ObservableCollection<Dashboard> dashboards = new ObservableCollection<Dashboard>();
dashboards.Add(new Dashboard { Name = "Dashboard1" });
dashboards.Add(new Dashboard { Name = "Dashboard2" });
Dashboards = dashboards;
}
}
}
Dashboard.cs
namespace WpfApp1
{
public class Dashboard
{
public string Name;
}
}
How do I get to create the buttons, am I on the right track with the ItemControl?
public string Name should be changed to be a public property to support data binding:
public class Dashboard
{
public string Name { get; set; }
}
Besides that, an instance of DashboardViewModel should be assigned to the Window's DataContext property and the ItemsControl's ItemsSource property should be bound like this:
<Window ...
xmlns:local="clr-namespace:WpfApp1">
<Window.DataContext>
<local:DashboardViewModel/>
</Window.DataContext>
<Grid>
<ItemsControl ItemsSource="{Binding Dashboards}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Content="{Binding Name}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</Window>
If necessary, you can access the view model instance in the Window's code behind like this:
var vm = (DashboardViewModel)DataContext;
vm.LoadDashboards();

Setting the DataContext to the current code-behind object in XAML

I'm trying to set the DataContext for my UserControl to the code-behind class of the UserControl. It's really easy to do from the code-behind side:
public partial class OHMDataPage : UserControl
{
public StringList Stuff { get; set; }
public OHMDataPage ()
{
InitializeComponent();
DataContext = this;
}
}
<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
x:Class="LCDHardwareMonitor.Pages.OHMDataPage">
<ScrollViewer>
<ListBox ItemsSource="{Binding Stuff}" />
</ScrollViewer>
</UserControl>
But how can I do this purely from the XAML side and at the UserControl level? It works on child nodes if I do this (and remove DataContext = this; from the code-behind):
<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
x:Class="LCDHardwareMonitor.Pages.OHMDataPage">
<ScrollViewer
DataContext="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}">
<ListBox ItemsSource="{Binding Stuff}" />
</ScrollViewer>
</UserControl>
I'd really like to understand how to do this on the UserControl itself. I expected this to work:
<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
x:Class="LCDHardwareMonitor.Pages.OHMDataPage"
DataContext="{Binding RelativeSource={RelativeSource Mode=Self}}">
<ScrollViewer>
<ListBox ItemsSource="{Binding Stuff}" />
</ScrollViewer>
</UserControl>
but it doesn't.
DataContext="{Binding Mode=OneWay, RelativeSource={RelativeSource Self}}"
Should work.
But if your properties are not set before InitializeComponent() is called, the WPF binding mechanism doesn't know that your property's values are changed.
To give you a quick idea:
// the binding should work
public StringList Stuff { get; set; }
public Constructor()
{
Stuff = new StringList { "blah", "blah", "foo", "bar" };
InitializeComponent();
}
// the binding won't work
public StringList Stuff { get; set; }
public Constructor()
{
InitializeComponent();
Stuff = new StringList { "blah", "blah", "foo", "bar" };
}
If you're using a list of strings, consider using an ObservableCollection instead. This will notify the WPF binding mechanism when items are added or removed.

Design time ItemsSource on ItemsControl

I'm trying to design the DataTemplate for my ItemsControl and I need some mock data to populate the template. I read using d:DataContext is enough so that I don't have to create a mock class. How can I do this?
The instance you have to use with d:DataContext must be declared in the XAML, with a StaticResource for example.
Here is how you could do it:
<UserControl x:Class="WpfApplication1.UserControl1"
xmlns:local="clr-namespace:WpfApplication1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<UserControl.Resources>
<local:MyViewModel x:Key="mockViewModel"/>
</UserControl.Resources>
<Grid>
<ItemsControl d:DataContext="{StaticResource mockViewModel}"
ItemsSource="{Binding Items}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</UserControl>
The class I used as data context is defined as follows:
namespace WpfApplication1
{
public class Item
{
public Item(string name)
{
Name = name;
}
public string Name { get; private set; }
}
public class MyViewModel
{
public List<Item> Items
{
get
{
return new List<Item>() { new Item("Thing 1"), new Item("Thing 2") };
}
}
}
}
Of course, you can also set the data context on the UserControl or on your Window.
Here's the result:

How to bind a property in the view model of a usercontrol to a property in another usercontrol

I am currently working within a WPF user control using MVVM. My MainWindow.xaml looks like below.
MainWindow.xaml
<Window.Resources>
<ObjectDataProvider x:Key="TabsList" ObjectType="{x:Type local:MainWindowModel}" MethodName="GetTabs"/>
</Window.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<ListBox Grid.Column="0" ItemsSource="{Binding Source={StaticResource TabsList}}" IsSynchronizedWithCurrentItem="True">
<ListBox.ItemTemplate>
<DataTemplate>
<Label Content="{Binding Path=TabName}" Margin="10"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<ContentControl Grid.Column="1" Content="{Binding Source={StaticResource TabsList}, Path=MyUserControl}"/>
</Grid>
Data provider class is as below
public class MainWindowModel
{
public List<TabInfo> GetTabs()
{
return new List<TabInfo>()
{
new TabInfo() { TabName="Tab1", MyUserControl = new UserControl1()},
new TabInfo() { TabName="Tab2", MyUserControl = new UserControl2()}
};
}
}
public class TabInfo
{
public string TabName { get; set; }
public UserControl MyUserControl { get; set; }
}
And now I have two usercontrols UserControl1 and UserControl2 each has a text box control. I would like to update the Text property of the textbox control in the UserControl1 whenever the Text property of the Textbox control in the UserControl2 is updated. To do this, I tried as below.
UserControl1
<UserControl x:Class="MoreOnBinding2.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<TextBox Width="200" Height="20" Text="{Binding Path=UserControl1Text}"/>
</Grid>
UserControl1ViewModel
public class UserControl1VM : ViewModelBase
{
public UserControl1VM()
{
this.UserControl1Text = "10";
}
private string userControl1Text;
public string UserControl1Text
{
get { return userControl1Text; }
set
{
if (userControl1Text != value)
{
userControl1Text = value;
RaisePropertyChanged(() => UserControl1Text);
}
}
}
}
UserControl2
<UserControl x:Class="MoreOnBinding2.UserControl2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:MoreOnBinding2"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<TextBox Width="200" Height="20"
Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type local:UserControl1}},
UpdateSourceTrigger=PropertyChanged, Path=UserControl1Text}" />
</Grid>
But it is not working. It seems there is a problem in the RelativeSource tag in the UserControl2. Can someone help on this.
You could use a Dependency Property on your user controls this would give you a bind able property. see link
EDIT 1
Just had another look at your class setup. If you are following the MVVM approach I don't think you should have a reference to your user control in your view model
View Model should be more Like
public Class
{
ObservableCollection<TabInfo> _Tabs = new ObservableCollection<TabInfo>();
public ObservableCollection<TabInfo> Tabs
{
get{return _Tabs;}
set {_Tabs = value;}//Need to implement INotifyPropertyChanged [Link][2]
}
public TabInfo SelectedTab {get;set;}
}
public class TabInfo
{
public string TabName { get; set; }
public UserControlViewModel MyUserControlViewModel{ get; set; }
}
Then in your View
<Window.DataContext>
<vm:MainWindowModel />
</Window.DataContext>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<ListBox Grid.Column="0" ItemsSource="{Binding Tabs}" IsSynchronizedWithCurrentItem="True" SelectedValue="{Binding SelectedTab}">
<ListBox.ItemTemplate>
<DataTemplate>
<Label Content="{Binding Path=TabName}" Margin="10"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<ContentControl Grid.Column="1" Content="{Binding SelectedTab.MyUserControlViewModel"/>
</Grid>
This should give you a list of Tabs and then when one is selected it will set the content of the ContentControl to the MyUserControlViewModel.
You would then need to use some sort of template selector to control the ContentTemplate to load different UserControls into the ContentControl
I haven't tested the code works and you would need to implement the INotifyPropertyChanged on all the public properties so the bindings update as the properties value is changed.
Hope that helps a bit.

Resharper dosn't recognize the correct ViewModel Type

We are using Resharper and of course we want to take advantage of Resharper's xaml intellisense.
Our View's Data Context are bound to a CurrentViewmodel property of type ViewModelBase. At runtime this Property is set with a View model inheritating from ViewModelBase.
I already added those lines in the View model to set the correct Type:
xmlns:vms="clr-namespace:PQS.ViewModel.Report"
d:DataContext="{d:DesignInstance vms:ReportFilterViewModel, IsDesignTimeCreatable=False}"
But Resharper still keeps looking in ViewModelbase for the Properties.
What else can i try?
Some more Code:
Setting the DataContext:
<UserControl.DataContext>
<Binding Path="ReportMainViewModel.CurrentVm" Source="{StaticResource Locator}"/>
</UserControl.DataContext>
Binding Something (Products is a Property on ReportFilterViewmodel, r# keeps looking for it in ViewModelBase):
<ListBox ItemsSource="{Binding Products.View}" Background="White" DisplayMemberPath="Name.ActualTranslation">
</ListBox>
R# can't statically find concrete view model type that will be available in runtime, so you need to annotate data context type manually like this:
using System.Collections.Generic;
public partial class MainWindow {
public MainWindow() {
Current = new ConcreteViewModel {
Products = {
new Product(),
new Product()
}
};
InitializeComponent();
}
public ViewModelBase Current { get; set; }
}
public class ViewModelBase { }
public class ConcreteViewModel : ViewModelBase {
public ConcreteViewModel() {
Products = new List<Product>();
}
public List<Product> Products { get; private set; }
}
public class Product {
public string ProductName { get { return "Name1"; } }
}
And XAML part:
<Window x:Class="MainWindow" x:Name="MainWin"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:global="clr-namespace:" mc:Ignorable="d"
DataContext="{Binding ElementName=MainWin, Path=Current}">
<!-- here the type of data context is ViewModelBase -->
<Grid d:DataContext="{d:DesignInstance global:ConcreteViewModel}">
<!-- and here is ConcreteViewModel -->
<ListBox ItemsSource="{Binding Path=Products}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding ProductName}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Window>
Or like this:
<Window x:Class="MainWindow" x:Name="MainWin"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:global="clr-namespace:"
DataContext="{Binding ElementName=MainWin, Path=Current}">
<Grid>
<ListBox ItemsSource="{Binding Path=(global:ConcreteViewModel.Products)}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding ProductName}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Window>

Categories