Binding a DataTemplate in a UserControl - user-controls

I'm writing a UserControl, which I intend to use on several pages. It should encapsulate the behaviour to be the same for all pages. But the content and the layout should be different.
On the UserControl I have a ListView whoes ItemSource is bound to a CollectionViewSource with grouping enabled.
<ListView
ItemSource="{Binding Source={StaticResource Collection}}"
ItemTemplate="{Binding GroupedDataTemplate}">
<ListView.GroupStyle>
<GroupSytele HeaderTemplate="{Binding HeaderDataTemplate}"/>
</ListView.GroupStyle>
</ListView>
The UserControl has the DependencyProperties "GroupedDataTemplate", "HeaderDataTemplate" for the layout and one "GroupedCollection" for the data.
On the page, where the UserControl is used, I defined the DataTemplates like:
<controls:MyUserControl
GroupedCollection="{Binding DataContext.MyDataCollection, ElementName=thePage}">
<controls:MyUserControl.GroupedDataTemplate>
<DataTemplate>
<TextBlock Text="{Binding Description}"/>
</DataTemplate>
</controls:MyUserControl.GroupedDataTemplate>
<controls:MyUserControl.HeaderDataTemplate>
<DataTemplate>
<TextBlock Text="{Binding Key}"/>
</DataTemplate>
</controls:MyUserControl.HeaderDataTemplate>
</controls:MyUserControl>
My problem is, that the DataTemplate definition for "GroupedDataTemplate" works as expected, the description is shown. But for the "HeaderDataTemplate" it doesn't, it is shown only the ToString()-representation of the object.
The setter of the "HeaderDataTemplate" is called and the DataTemplate is assigned to the DependencyProperty of the UserControl.
If I replace the UserControl with the ListView itself, it works as expceted. Thus the binding works propperly to the Description and the Key, but it will only work for description if it is inside the UserControl.
For test purposes I have added a converter to the binding of the Key in the page and it is never called. I all cases, where I define a DataTemplate for an ItemTemplate (ListView or GridView) it works, but is doesn't for the HeaderTemplate of the GroupStyle.
What is my fault?

Very good question, it seems when you use Binding for the HeaderTemplate of GroupSytele, in the .g.cs file of your UserControl, it doesn't generate the update code for HeaderDataTemplate, it means when you define this HeaderDataTemplate property for example like this:
public static readonly DependencyProperty HeaderDataTemplateProperty = DependencyProperty.Register("HeaderDataTemplate", typeof(DataTemplate), typeof(UserGroupedListView), new PropertyMetadata(null));
public DataTemplate HeaderDataTemplate
{
get { return (DataTemplate)GetValue(HeaderDataTemplateProperty); }
set { SetValue(HeaderDataTemplateProperty, value); }
}
The get never gets called.
A workaround here is that you can change the Binding to x:Bind like this in your UserControl:
<ListView ItemsSource="{Binding Source={StaticResource Collection}}" ItemTemplate="{Binding GroupedDataTemplate}">
<ListView.GroupStyle>
<GroupStyle HeaderTemplate="{x:Bind HeaderDataTemplate}" />
</ListView.GroupStyle>
</ListView>
Basically you've done nothing wrong, but it seems data binding for the HeaderTemplate of GroupStyle can only work when it uses x:Bind.

Related

UWP, Apply a converter to a ListView's item when the ListView's items source is a collection of strings

I have the following situation. I want to show a list of strings. In order to achieve that, I have a ListView bound to a collection of strings. In this collection, there are some empty strings. What I want is to show the following text when a empty string is present: "-empty-". This is what I got so far (the source code is for demonstration purpose only):
EmptyStringConverter.cs
public class EmptyStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
if (value is string && string.IsNullOrWhiteSpace((string)value))
{
return "-empty-";
}
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
MainPage.xaml
<Page
x:Class="App1.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App1"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Page.Resources>
<local:EmptyStringConverter x:Key="EmptyStringConverter" />
</Page.Resources>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<ListView x:Name="ListView">
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Converter={StaticResource EmptyStringConverter}}" Margin="0,0,0,5" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
</Page>
MainPage.xaml.cs
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
var source = new[] { "", "String 1", "String 2" };
ListView.ItemsSource = source;
}
}
When a put a breakpoint in the Convert method in EmptyStringConverter class, the method is called in every single item except in the empty string. How can I achieve what I want?
Well the issue was in the place I'd check the last. It's your Legacy Binding that's causing the issue. I tried a code snippet myself and then I replaced it with yours piece by piece. The below line uses legacy binding
Text="{Binding Converter={StaticResource EmptyStringConverter}}"
Since you are using UWP you can switch to a Compile time binding that'll fix your problem your modified ListView XAML would be:
<ListView x:Name="ListView" >
<ListView.ItemTemplate>
<DataTemplate x:DataType="x:String">
<TextBlock Text="{x:Bind Converter={StaticResource EmptyStringConverter},Mode=OneTime}" Margin="0,0,0,5" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Please pay attention at two things:
the Text section of the Textbox in the DataTemplate, it uses x:Bind instead of Binding. Please do note that compile time binding is a oneTime binding by default (unless you explicitly mention the Mode) where as the Legacy Binding is a OneWay binding by default. For More information on compile time binding follow: xBind markup extension.
If you notice the DataTemplate declaration holds a DataType property, that helps the compile time binder to know what kind of data is it expecting. For more information on DataType follow: xBind markup extension.
All that being said, I would highly recommend using the Data Binding approach instead of the ListView.ItemSource=source as with the new Compile Time binding, alot of conversions are handled by the binding engine itself leading to less code and effort on your end. I've put up a sample on github for the same you can check it out: EmptyStringDemo

XAML - Declare string, with Textbox.Text as value

kinda new to XAML, but I was wondering if it's possible to declare a string variable which contains the value of a Textbox.Text.
<System:String x:Key="AlarmMessage01">
<!-- Textbox text goes here --->
</System:String>
I'm not looking for a solution which depends on code-behind, purely XAML code, and I don't want to enter a static value either.
Can this even be done, and if so could you show me an example?
Kind regards Cvr
<Page.Resources>
<x:String x:Key="myStaticString" >Hello World</x:String>
</Page.Resources>
<TextBlock Text="{StaticResource myStaticString}" />
I have tested it in WinRT or Windows Store projects
If what you need is a value that can be updated dynamically, you can use Dynamic Resources or Data Binding
With Data Binding(this is probably the best approach):
In your ViewModel class:
public string TextBoxValue { get; set; }
public ViewModel(string text)
{
TextBoxValue = text;
}
In your Code-Behind:
public CurrentPage()
{
this.BindingContext = new ViewModel("Text to be displayed");
}
In your XAML file:
<TextBlock Text="{Binding TextBoxValue}" />
And that's that about it.
Meanwhile, if you want to go with Dynamic Resources:
In code-behind file(wherever you want to update the value), you have:
this.Resources["myStringValue"] = "Text to be displayed";
And in XAML, you have:
<TextBlock Text="{DynamicResource myStringValue}" />

UserControl embeding free XAML content

I would like to create a User Control which can embed free content.
I created a Dependency property for the content :
public sealed partial class MyUserControl : UserControl
{
public Border MyProperty
{
get { return (Border)GetValue(MyPropertyProperty); }
set { SetValue(MyPropertyProperty, value); }
}
public static readonly DependencyProperty MyPropertyProperty =
DependencyProperty.Register("MyProperty", typeof(Border), typeof(VisitList), new PropertyMetadata(new Border() { Height=300, Width=300 }));
...
}
So In my MainPage.xaml, I can use it with following code :
<MyUserControl>
<MyUserControl.MyProperty>
<Border x:Name="MyContent" Width="60" Height="60" Background="Pink">
... Whatever ...
</Border>
</MyUserControl.MyProperty>
</MyUserControl>
From this, I can't find what is the XAML syntax in the MyUserControl.xaml for declaring the placeholder that will be substituted by MyContent at runtime.
I tried with :
<UserControl ... >
....
<Grid ...>
<ContentPresenter Content="{TemplateBinding MyProperty}" />
</Grid>
</UserControl>
But, it crashes with message :
An exception of type 'Windows.UI.Xaml.Markup.XamlParseException' occurred in xXx.exe but was not handled in user code
WinRT information: Failed to create a 'Windows.UI.Xaml.DependencyProperty' from the text 'MyProperty'. [Line: 29 Position: 35]
(The Line: 29 Position:35 refers to Content="{TemplateBinding MyProperty}")
It sounds like you're mixing Templated Controls and UserControls. It's a bit complicated, but basically, TemplateBindings work when they're apart of the ContentTemplate of the control, as opposed to the Content itself (which is what I believe is happening here, based on the xaml you have shown).
Try changing your bindings in this way:
<UserControl x:Name="RootControl" ...>
....
<ContentControl Content="{Binding MyProperty, ElementName=RootControl}" />
....
</UserControl>
What this means is that you will need to have your UserControl implement INotifyPropertyChanged in case it needs to respond to changing Content.

WPF: Cannot bind to a custom controls dependency property

I've created a custom control with a dependency property for databinding.
The binded value should then be displayed in a text box.
This binding works properly.
The problem occurs when I implement my custom control. The grid's data context is a simple view model which contains a String property for binding.
If I bind this property to a standard wpf controls text box everything works fine.
If I bind the property to my custom control nothing happens.
After some debugging I found out that SampleText is searched in CustomControl. Of course it doesn't exist there.
Why is my property searched in CustomControl and not taken from the DataContext as it happens in scenario 1.
<Window x:Class="SampleApplicatoin.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:controls="clr-namespace:SampleApplication"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.DataContext>
<controls:ViewModel/>
</Grid.DataContext>
<TextBox Text="{Binding SampleText}"/>
<controls:CustomControl TextBoxText="{Binding SampleText}"/>
</Grid>
</Window>
Below the XAML code of the custom control.
I use DataContext = Self to get the dependency property from code behind:
<UserControl x:Class="SampleApplication.CustomControl"
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" DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Grid>
<TextBox HorizontalAlignment="Left" Height="23" Margin="87,133,0,0" TextWrapping="Wrap" Text="{Binding TextBoxText}" VerticalAlignment="Top" Width="120"/>
</Grid>
</UserControl>
The xaml.cs file just contains the dependency property:
public partial class CustomControl : UserControl
{
public static readonly DependencyProperty TextBoxTextProperty = DependencyProperty.Register("TextBoxText", typeof (String), typeof (CustomControl), new PropertyMetadata(default(String)));
public CustomControl()
{
InitializeComponent();
}
public String TextBoxText
{
get { return (String) GetValue(TextBoxTextProperty); }
set { SetValue(TextBoxTextProperty, value); }
}
}
Thanks for any help on this. It really drives me crazy now.
EDIT:
I just came over two possible solutions:
Here the first (which works for me):
<!-- Give that child a name ... -->
<controls:ViewModel x:Name="viewModel"/>
<!-- ... and set it as ElementName -->
<controls:CustomControl TextBoxText="{Binding SampleText, ElementName=viewModel}"/>
The second one. This doesn't work in my case. I don't know why:
<controls:CustomControl TextBoxText="{Binding SampleText, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type controls:ViewModel}}}"/>
<!-- or -->
<controls:CustomControl TextBoxText="{Binding SampleText, RelativeSource={RelativeSource FindAncestor, AncestorType=controls:ViewModel}}"/>
I had a similar situation.
In my case, I fixed it with adding OnPropertyChanged in setter of property in ViewModel.

update view from another one the same viewmodel

I am new to the MVVM philosophy, and my question may be stupid but hey, I try anyway.
I have a view associated with a model view. In this view, I open a dialog box when the user presses a button.
From this dialog box, I want to refresh the main view without closing the dialog.
The dialog and the main view share the same view model, and I have a property that is binded in the main view.
But when I change the binded property from from the dialog, it is well updated, but not the main view.
Here some code:
MainView.xaml:
<TextBox x:Name="tnNomModele"
HorizontalAlignment="Left"
Height="23"
Margin="142,35,0,0"
TextWrapping="Wrap"
VerticalAlignment="Top"
Width="143"
Text="{Binding MyProperty, UpdateSourceTrigger=PropertyChanged}"/>
ViewModel.cs
public string MyProperty
{
get
{
return _mystring ;
}
set
{
_mystring = value;
RaisePropertyChanged("MyProperty");
}
}
Here's how I call the dialog, on the command binded with a button on the main view:
MyDialog diag = new MyDialog ();
diag.ShowDialog();
And in the command binded with a button on the dialog, I change the value of MyProperty.
But nothing happens in the main view...
I think you need to change your binding:
<TextBox x:Name="tnNomModele" HorizontalAlignment="Left" Height="23" Margin="142,35,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="143" Text="{Binding MyProperty,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
The change is that you're using the default Binding mode, which is OneWay. This means that the ViewModel can push changes to the View but will not receieve changes made from the View. Using TwoWay means that the ViewModel receives notifications from the View when a property changes.

Resources