How to instantiate DataContext object in XAML - c#

I want to be able to create an instance of the DataContext object for my WPF StartupUri window in XAML, as opposed to creating it code and then setting the DataContext property programmaticly.
The main reason is I don't need to access the object created externally and I don't want to have to write code behind just for setting the DataContext.
I'm sure I've read somewhere how to instantiate the DataContext object in XAML but I can't find it in any of the usual places...

You add an XML namespace for whatever namespace your DataContext lives in, create an instance of it in the Window Resources and set the DataContext to that resource:
<Window x:Class="WpfApplication4.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication4"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<local:MyViewModel x:Key="MyViewModel"/>
</Window.Resources>
<Grid DataContext="{StaticResource MyViewModel}">
</Grid>
</Window>

You can just specify this directly in XAML for the entire Window:
<Window
... xmlns definitions ...
>
<Window.DataContext>
<local:CustomViewModel />
</Window.DataContext>
</Window>
This creates a view model named "CustomViewModel" in the namespace aliased to local, directly as the DataContext for the Window.

Assuming this code:
public abstract class BaseView { }
public class RuntimeView : BaseView { }
public class DesigntimeView : BaseView { }
Try this:
<Page.DataContext>
<local:RuntimeView />
</Page.DataContext>
<d:Page.DataContext>
<local:DesigntimeView />
</d:Page.DataContext>
<ListBox ItemsSource="{Binding}" />
Best of luck!

If you need to set the DataContext as same control class:
<Window x:Class="TabControl.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TabControl"
Title="MainWindow" Height="350" Width="525"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
>
</Window>
use RelativeSource binding.
or just
<Window x:Class="TabControl.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TabControl"
Title="MainWindow" Height="350" Width="525"
>
<Window.DataContext>
< new instance of any viewModel here....>
</Window.DataContext>
</Window>
If want to assign an instance of different class than itself.

Related

Trying to set root element to SynchronousMode but says does not exist in xaml namespace

I am trying to load a loose xaml using LoadAsync method
but in xaml file when setting the root element to x:SynchronousMode="Async"
it complains. It says SynchronousMode does not exist in xaml namespace
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" x:SynchronousMode="Async" >
<Grid>
<Button x:Name="okButton" x:FieldModifier="public" >OK</Button>
</Grid>
</Window>

Default value for property of UserControl

UserControl contains BorderBrush property derived from Control. How can I setup it's default value, for example, to Brushes.Black and make it available to be set by developer who will use my control?
I tried to assign initial value in <UserControl> tag in control's xaml file and in constructor of it, but when I do any of this, value assigned for the control
externally is ignored.
You would usually do this by overriding metadata for the BorderBrush property in your UserControl derived class:
public partial class MyUserControl : UserControl
{
static MyUserControl()
{
BorderBrushProperty.OverrideMetadata(
typeof(MyUserControl),
new FrameworkPropertyMetadata(Brushes.Black));
}
public MyUserControl()
{
InitializeComponent();
}
}
Perhaps styles would be best. You could create a new UserControl, let's call it BorderedControl. I've created a new folder called Controls to hold it.
<UserControl x:Class="BorderTest.Controls.BorderedControl"
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>
</Grid>
</UserControl>
Next, create a Resource Dictionary, UserControlResources. Be sure to include the namespace of the control:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ctrls="clr-namespace:BorderTest.Controls">
<Style TargetType="{x:Type ctrls:BorderedControl}">
<Setter Property="BorderBrush" Value="Lime"/>
<Setter Property="BorderThickness" Value="3"/>
</Style>
</ResourceDictionary>
Here you can set what ever properties you'd like to have default.
Then, include the resource dictionary in the user control resources:
<UserControl x:Class="BorderTest.Controls.BorderedControl"
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>
<ResourceDictionary Source="/BorderTest;component/Resources/UserControlResources.xaml"/>
</UserControl.Resources>
<Grid>
</Grid>
</UserControl>
Finally, add the control to your main window:
<Window x:Class="BorderTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ctrls="clr-namespace:BorderTest.Controls"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ctrls:BorderedControl Width="100"
Height="100"/>
</Grid>
</Window>
Here is my solution:
Here is the application when you run it:
You can simply change the border of your user control with this:
<ctrls:BorderedControl Width="100"
Height="100"
BorderBrush="Orange"/>

WPF Binding inner control with parent data context

I made a user control
<UserControl x:Class="MyApp.MyControl"
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" x:Name="uc">
<Grid Width="Auto" Height="Auto">
<TextBlock Text="{Binding Path=DataContext.TextContent, ElementName=uc}"/>
<TextBlock Text="{Binding Path=DataContext.TextContent2, ElementName=uc}"/>
</Grid>
I want the sub-controls in the defined control(uc) will bind to the properties of uc.DataContext. I used the defined control as follows:
<Window x:Class="Tms.TMSClient.Views.MainWindow" Name="window"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:control="clr-namespace:MyApp"
xmlns:ribbon="clr-namespace:Microsoft.Windows.Controls.Ribbon;assembly=RibbonControlsLibrary">
<control:MyControl DataContext="{Binding Path=MyControlVM}"/>
The DataContext which is assigned to the window has this structure: WindowVM.MyControlVM.TextContent.
The given code does not work because the textbox's DataContext is bound to WindowVM instead. I think the problem may be because the inner textbox is bound before the defined control (uc) is, thus the bounded DataContext for uc does not take effect yet.
What I want is: the custom control (MyControl) will be bound to its corresponding viewmodel (MyControlVM), and the inner elements of MyControl will be bound to the properties of MyControlVM.
Do you have any solutions for this problem?
If I understand you correctly, you want to data bind a property from your MyControl view model to a TextBox.Text property inside the MyControl UserControl. If that is correct, then you can use a RelativeSource Binding, or the ElementName syntax that you are already using.
First, make sure that your view model is set as the DataContext for the UserControl:
public MyControl()
{
DataContext = new YourControlViewModel();
}
As child controls automatically inherit their parent's DataContext objects, you can now reference this view model from the TextBox through the MyControl.DataContext property from the UserControl's XAML:
<TextBlock Text="{Binding DataContext.TextContent,
RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />
That's all you need.
<TextBlock Text="{Binding Path=TextContent}"/>
works for me in my test-application.
MainWindow.xaml
<Window x:Class="DataContextTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:my="clr-namespace:DataContextTest"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<my:MyOuterDataContext />
</Window.DataContext>
<Grid>
<my:MyControl DataContext="{Binding Path=MyInnerDataContext}" />
</Grid>
MyControl.xaml
<UserControl x:Class="DataContextTest.MyControl"
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>
<TextBlock Text="{Binding Path=TextContent}" />
</Grid>
DataContexts:
public class MyOuterDataContext
{
public MyInnerDataContext MyInnerDataContext { get; set; }
public MyOuterDataContext()
{
MyInnerDataContext = new MyInnerDataContext();
}
}
public class MyInnerDataContext
{
public string TextContent { get { return "foo"; } }
}
By default every control inherits its DataContext from its parent control. Thus there is no need to explicitly bind to it.
Indeed, when you want to bind a control's DataContext to a nested property then you have to specifiy this:
<control:MyControl DataContext="{Binding Path=TextContent}"/>

Showing a control based on type of databound viewmodel?

I'm learning WPF at the moment. I'm finding xaml quite tough to use. I have MainWindow.xaml defined like this:
<Window x:Class="Compliance.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<ResourceDictionary Source="MainWindow.Resources.xaml"></ResourceDictionary>
</Window.Resources>
<Grid>
</Grid>
</Window>
And MainWindow.Resources.xaml like this:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:Compliance.ViewModel"
xmlns:vw="clr-namespace:Compliance.View">
<DataTemplate DataType="{x:Type vm:Entities.AbstractEntityViewModel}">
<vw:AbstractEntityView></vw:AbstractEntityView>
</DataTemplate>
</ResourceDictionary>
AbstractEntityView is like this:
<UserControl x:Class="Compliance.View.AbstractEntityView"
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">
<StackPanel>
<Label Content="ID:"></Label>
<TextBlock Text="{Binding Path=EntityId}"></TextBlock>
</StackPanel>
</UserControl>
Then in App.xaml.cs I am overriding OnStartup like this:
MainWindow window = new MainWindow();
//Model class
Individual ind = new Individual(1,"Name");
//subclass of AbstractEntityViewModel
var vm = new Entities.IndividualEntityViewModel(ind);
window.DataContext = vm;
window.Show();
However, nothing appears in the window.
I used the answer from this question to get my control to render. However, this requires you to refer to elements in the view from the code, which I don't want to do.
Is it possible to get a window to pick a View to render based on the ViewModel set as its datacontext? Or do I have the wrong idea about how MVVM is supposed to work?
You have the right idea, but you're not actually telling WPF to display your ViewModel anywhere
I usually host a ViewModel in a ContentControl object if I am binding to a single ViewModel
<Window x:Class="Compliance.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<ResourceDictionary Source="MainWindow.Resources.xaml"></ResourceDictionary>
</Window.Resources>
<Grid>
<ContentControl Content="{Binding }" />
</Grid>
</Window>
The ContentControl is usually not needed for lists of Models or ViewModels, since the object is automatically inserted as the Content property of the ContentPresenter of each item. For example, no ContentControl is needed when binding a ListBox to a collection of ViewModels
<ListBox ItemsSource="{Binding MyCollectionOfViewModel}" />

Mistake in simple XAML binding

Why doesn't this binding update?
code:
MainWindow.xaml
<Window x:Class="WpfApplication12.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication12"
Height="350" Width="525">
<StackPanel>
<local:UserControl1 x:Name="usr" />
<TextBlock Text="{Binding ElementName=usr, Path=txt.Text}" />
</StackPanel>
</Window>
UserControl1.xaml
<UserControl x:Class="WpfApplication12.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<TextBox Text="qwe" x:Name="txt" />
</UserControl>
The TextBox inside the UserControl is inaccessible due to its protection level, also it is a field, you can never bind to those. You would need to expose it in the code behind of the UserControl as public property.
public TextBox Txt
{
get { return txt; }
}
Edit: As Henk Holterman pointed out you might not want to expose the whole TextBox, so you could define a dependency property to which the TextBox internally binds for example.

Categories

Resources