WPF - Properties of ItemsSource to Dependency Properties - c#

Background
I am making a custom control that has multiple ListBox's. I want to make this control MVVM compliant, so I am keeping any XAML and the code behind agnostic with respect to any ViewModel. One ListBox is simply going to be a list of TextBox's while the other is going to have a canvas as the host to display the data graphically. Both of these ListBox's are children of this custom control.
Pseudo example for the custom control template:
<CustomControl>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<ListBox1 Grid.Column="0"/>
<ListBox2 Grid.Column="1"/>
</CustomControl>
The code behind for this custrom control would have a dependency property that will serve as the ItemsSource, fairly standard stuff:
public IEnumerable ItemsSource
{
get { return (IEnumerable)GetValue(ItemsSourceProperty); }
set { SetValue(ItemsSourceProperty, value); }
}
public static readonly DependencyProperty ItemsSourceProperty =
DependencyProperty.Register("ItemsSource", typeof(IEnumerable), typeof(UserControl1), new PropertyMetadata(new PropertyChangedCallback(OnItemsSourcePropertyChanged)));
private static void OnItemsSourcePropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var control = sender as UserControl1;
if (control != null)
control.OnItemsSourceChanged((IEnumerable)e.OldValue, (IEnumerable)e.NewValue);
}
Where I am stuck
Because the two ListBox's are using the same data source but just display the data differently, I want the ItemsSource defined as one of the the parent view's dependency properties to be the ItemsSource for the two children. From the ViewModel side, this items source can be some sort of ObservableCollection<ChildViewModels>, or IEnumerable, or whatever it wants to be.
How can I point to properties from the ItemsSource's ViewModel to dependency properties of the child views?
I was hoping to get something similar to how it could be done outside of a custom view:
Example Parent ViewModel(omitting a lot, assume all functioning):
public class ParentViewModel
{
public ObservableCollection<ChildViewModel> ChildViewModels;
}
Example ViewModel (omitting INotifyPropertyChanged and associated logic):
public class ChildViewModel
{
public string Name {get; set;}
public string ID {get; set;}
public string Description {get; set;}
}
Example control (ommitting setting the DataContext, assume set properly):
<ListBox ItemsSource="{Binding ChildViewModels}">
<ListBox.ItemsTemplate>
<StackPanel>
<TextBlock Text="{Binding Name}"/>
<TextBlock Text ="{Binding Description}"/>
</StackPanel>
</ListBox.ItemsTemplate>
</ListBox>
How can I do something similar where I can pass the properties from the ItemsSource to the child views on a custom control?
Many thanks

If I understand correctly what you need, then here is an example.
Add properties for element templates in both lists and style for Canvas.
using System.Collections;
using System.Windows;
using System.Windows.Controls;
namespace Core2022.SO.jgrmn
{
public class TwoListControl : Control
{
static TwoListControl()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(TwoListControl), new FrameworkPropertyMetadata(typeof(TwoListControl)));
}
public IEnumerable ItemsSource
{
get { return (IEnumerable)GetValue(ItemsSourceProperty); }
set { SetValue(ItemsSourceProperty, value); }
}
public static readonly DependencyProperty ItemsSourceProperty =
DependencyProperty.Register(
nameof(ItemsSource),
typeof(IEnumerable),
typeof(TwoListControl),
new PropertyMetadata((d, e) => ((TwoListControl)d).OnItemsSourceChanged((IEnumerable)e.OldValue, (IEnumerable)e.NewValue)));
private void OnItemsSourceChanged(IEnumerable oldValue, IEnumerable newValue)
{
//throw new NotImplementedException();
}
public DataTemplate TemplateForStack
{
get { return (DataTemplate)GetValue(TemplateForStackProperty); }
set { SetValue(TemplateForStackProperty, value); }
}
public static readonly DependencyProperty TemplateForStackProperty =
DependencyProperty.Register(
nameof(TemplateForStack),
typeof(DataTemplate),
typeof(TwoListControl),
new PropertyMetadata(null));
public DataTemplate TemplateForCanvas
{
get { return (DataTemplate)GetValue(TemplateForCanvasProperty); }
set { SetValue(TemplateForCanvasProperty, value); }
}
public static readonly DependencyProperty TemplateForCanvasProperty =
DependencyProperty.Register(
nameof(TemplateForCanvas),
typeof(DataTemplate),
typeof(TwoListControl),
new PropertyMetadata(null));
public Style StyleForCanvas
{
get { return (Style)GetValue(StyleForCanvasProperty); }
set { SetValue(StyleForCanvasProperty, value); }
}
public static readonly DependencyProperty StyleForCanvasProperty =
DependencyProperty.Register(
nameof(StyleForCanvas),
typeof(Style),
typeof(TwoListControl),
new PropertyMetadata(null));
}
}
In the theme (Themes/Generic.xaml), set bindings to these properties:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:jgrmn="clr-namespace:Core2022.SO.jgrmn">
<Style TargetType="{x:Type jgrmn:TwoListControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type jgrmn:TwoListControl}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<ListBox Grid.Column="0"
ItemsSource="{TemplateBinding ItemsSource}"
ItemTemplate="{TemplateBinding TemplateForStack}"/>
<ListBox Grid.Column="1"
ItemsSource="{TemplateBinding ItemsSource}"
ItemTemplate="{TemplateBinding TemplateForCanvas}"
ItemContainerStyle="{TemplateBinding StyleForCanvas}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ListBox>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
Window with an example of use:
<Window x:Class="Core2022.SO.jgrmn.TwoListWindow"
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:local="clr-namespace:Core2022.SO.jgrmn"
mc:Ignorable="d"
Title="TwoListWindow" Height="250" Width="400">
<FrameworkElement.DataContext>
<CompositeCollection>
<Point>15 50</Point>
<Point>50 150</Point>
<Point>150 50</Point>
<Point>150 150</Point>
</CompositeCollection>
</FrameworkElement.DataContext>
<Grid>
<local:TwoListControl ItemsSource="{Binding}">
<local:TwoListControl.TemplateForStack>
<DataTemplate>
<TextBlock>
<TextBlock.Text>
<MultiBinding StringFormat="{}Point ({0} {1})">
<Binding Path="X"/>
<Binding Path="Y"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</DataTemplate>
</local:TwoListControl.TemplateForStack>
<local:TwoListControl.TemplateForCanvas>
<DataTemplate>
<Ellipse Width="10" Height="10" Fill="Red"/>
</DataTemplate>
</local:TwoListControl.TemplateForCanvas>
<local:TwoListControl.StyleForCanvas>
<Style TargetType="ListBoxItem">
<Setter Property="Canvas.Left" Value="{Binding X}"/>
<Setter Property="Canvas.Top" Value="{Binding Y}"/>
</Style>
</local:TwoListControl.StyleForCanvas>
</local:TwoListControl>
</Grid>
</Window>

You must spend all participating controls a ItemsSource property. The idea is to delegate the source collection from the parent to the child controls and finally to the ListBox. The ItemsSource properties should be a dependency property of type IList and not IEnumerable. This way you force the binding source to be of type IList which improves the binding performance.
To allow customization of the actual displayed items, you must either
a) spend every control a ItemTemplate property of type DataTemplate and delegate it to the inner most ListBox.ItemTemplate (similar to the ItemsSource property) or
b) define the template as a resource (implicit template, which is a key less DataTemplate).
The example implements a):
<Window>
<Window.DataContext>
<ParentViewModel />
</Window.DataCOntext>
<CustomControl ItemsSource="{Binding ChildViewModels}">
<CustomControl.ItemsTemplate>
<StackPanel>
<TextBlock Text="{Binding Name}"/>
<TextBlock Text ="{Binding Description}"/>
</StackPanel>
</CustomControl.ItemsTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<ListBox1 Grid.Column="0"
ItemsSource="{Binding RelativeSource={RelativeSource AncestorType=UserControl}, Path=ItemsSource}"
ItemTemplate="{Binding RelativeSource={RelativeSource AncestorType=UserControl}, Path=ItemTemplate}" />
<ListBox2 Grid.Column="1"
ItemsSource="{Binding RelativeSource={RelativeSource AncestorType=UserControl}, Path=ItemsSource}"
ItemTemplate="{Binding RelativeSource={RelativeSource AncestorType=UserControl}, Path=ItemTemplate}" />
</CustomControl>
</Window>
Inside the child controls (ListBox1 and ListBox2):
<UserControl>
<ListBox ItemsSource="{Binding RelativeSource={RelativeSource AncestorType=UserControl}, Path=ItemsSource}"
ItemTemplate="{Binding RelativeSource={RelativeSource AncestorType=UserControl}, Path=ItemTemplate}" />
</UserControl>

Related

get child nodes of node WPF

I have created this UserControl
public partial class Dropdown : UserControl
{
public string Title { get; set; } = string.Empty;
private void loadSuccess(object sender, RoutedEventArgs e)
{
TitleBlock.Text = Title;
}
public Dropdown()
{
Loaded += loadSuccess;
InitializeComponent();
}
}
<UserControl x:Class="Lamprey.UserControls.Dropdown"
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:Lamprey.UserControls"
mc:Ignorable="d"
>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="17"></ColumnDefinition>
<ColumnDefinition Width="*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="auto"></RowDefinition>
<RowDefinition Height="auto"></RowDefinition>
</Grid.RowDefinitions>
<TextBlock Text=">" Grid.Row="0" Grid.Column="0" Foreground="#FFC7C7C7"></TextBlock>
<TextBlock x:Name="TitleBlock" Grid.Row="0" Grid.Column="1"></TextBlock>
<ListBox x:Name="Items" Grid.Column="1" Grid.Row="1" Background="{x:Null}" BorderBrush="{x:Null}" Foreground="White">
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Focusable" Value="False"/>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
</Grid>
</UserControl>
It is meant to be used like this
<usercontrols:Dropdown Title="History">
<ListBoxItem>
<TextBlock>Example</TextBlock>
</ListBoxItem>
</usercontrols:Dropdown>
I am trying to figure out how I can get a list of children of the <Dropdown> so I can move them into the Items <ListBox>.
The end goal is for any children addded to <Dropdown> to be automatically added to the <ListBox> named Items. That way, the entire listbox can be hidden when the dropdown is closed, and shown when the dropdown is opened.
The key is to define a collection dependency property and bind it to the ListBox. This property must be declared as the control's content property in order to be able to add items to it implicitly in XAML.
Define a custom non-generic collection or use an existing one
DropDownItemCollection.cs
public class DropDownItemCollection : List<object>
{ }
Define a dependency property of the non-generic collection type
Declare this property as the content property using the ContentProperty attribute to decorate the property owner
Optionally, define a DataTemplate type property e.g., ItemTemplate to allow templating the items using an explicit DataTemplate
DropDown.xaml.cs
[ContentProperty(nameof(DropDown.DropDownItems))]
public partial class DropDown : UserControl
{
public DropDownItemCollection DropDownItems
{
get => (DropDownItemCollection)GetValue(DropDownItemsProperty);
set => SetValue(DropDownItemsProperty, value);
}
public static readonly DependencyProperty DropDownItemsProperty =
DependencyProperty.Register(
"DropDownItems",
typeof(DropDownItemCollection),
typeof(DropDown),
new PropertyMetadata(default));
public DataTemplate ItemTemplate
{
get => (DataTemplate)GetValue(ItemTemplateProperty);
set => SetValue(ItemTemplateProperty, value);
}
public static readonly DependencyProperty ItemTemplateProperty =
DependencyProperty.Register(
"ItemTemplate",
typeof(DataTemplate),
typeof(DropDown),
new PropertyMetadata(default));
public DropDown()
{
InitializeComponent();
this.DropDownItems = new DropDownItemCollection();
}
}
Bind the internal ListBox to the new DropDownItems property
DropDown.xaml
<UserControl>
<ListBox ItemsSource="{Binding RelativeSource={RelativeSource AncestorType=UserControl}, Path=DropDownItems}"
ItemTemplate="{Binding RelativeSource={RelativeSource AncestorType=UserControl}, Path=ItemTemplate}" />
</UserControl>
Example
<!--
Since the collection is of type object you can add anything to the collection.
The ItemTemplate property allows to explicitly template the item layout.
-->
<Window>
<Window.Resources>
<DataTemplate x:Key="DroptDownItemTemplate">
<Grid>
<Border Background="OrangeRed" />
<TextBlock Text="{Binding}" />
</Grid>
</DataTemplate>
</Window.Resources>
<DropDown ItemTemplate={StaticResource DroptDownItemTemplate}">
<sys:String>Item 1</sys:String>
<sys:String>Item 2</sys:String>
</DropDown>
</Window>
Remarks
You can skip all this when extending ListBox instead of UserControl. Doing so, your control will support item creation in XAML and templating out of the box.
Hiding and showing the internal ListBox will lead to changes in the layout and therfore result in ugly content resizing. You should consider to host the ListBox (or in case of extending ListBox the ItemsPresenter) inside a Popup to create the flyout that overlays instead of resizing.

How to fill each tab of the tab control's itemslist with one user control dynamically from the mainviewmodel

My MainView contains a TabControl with an ItemTemplate and a ContentTemplate.
The TabControl's ItemsSource is bound to the Property ObservableCollection<TabViewModel> TabCollection in my MainViewModel.
TabViewModel:
namespace LuxUs.ViewModels
{
public class TabViewModel
{
public string Name { get; set; }
public object VM {get; set;}
public TabViewModel(string name)
{
Name = name;
}
public TabViewModel(string name, object vm)
{
Name = name;
VM = vm;
}
}
}
I want to create the tabs with their tab's header AND content dynamically from the MainViewModel like this...:
MainViewModel:
using System.Collections.ObjectModel;
namespace LuxUs.ViewModels
{
public class MainViewModel : ObservableObject, IPageViewModel
{
public ObservableCollection<TabViewModel> TabCollection { get; set; }
public MainViewModel()
{
TabCollection = new ObservableCollection<TabViewModel>();
TabCollection.Add(new TabViewModel("Dachdefinition", new DachdefinitionViewModel()));
TabCollection.Add(new TabViewModel("Baukörperdefinition"));
TabCollection.Add(new TabViewModel("Fassade"));
TabCollection.Add(new TabViewModel("Raumdefinition"));
TabCollection.Add(new TabViewModel("Treppenloch | Galerieöffnung"));
}
}
}
View:
<UserControl x:Class="LuxUs.Views.MainView"
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:LuxUs.Views"
xmlns:models="clr-namespace:LuxUs.Models"
xmlns:vm="clr-namespace:LuxUs.ViewModels"
mc:Ignorable="d">
<Grid>
<Grid>
<TabControl Style="{DynamicResource TabControlStyle}" ItemsSource="{Binding TabCollection}" >
<TabControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</TabControl.ItemTemplate>
<TabControl.ContentTemplate>
<DataTemplate>
<UserControl>
<ContentControl Content="{Binding VM}" />
</UserControl>
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
</Grid>
</Grid>
</UserControl>
... but the content of each tab won't show. Instead, I get this text. The ViewModel ist the correct one but it should load the view instead of showing this text, of course:
The first tab's ViewModel DachdefinitionViewModel has only an empty constructor:
using System.Collections.ObjectModel;
namespace LuxUs.ViewModels
{
public sealed class DachdefinitionViewModel : ObservableObject
{
public DachdefinitionViewModel()
{
}
}
}
And here is its view Dachdefinition.xaml:
<UserControl x:Class="LuxUs.Views.Dachdefinition"
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:LuxUs.Views"
xmlns:vm="clr-namespace:LuxUs.ViewModels"
mc:Ignorable="d">
<UserControl.DataContext>
<vm:DachdefinitionViewModel></vm:DachdefinitionViewModel>
</UserControl.DataContext>
<Grid Margin="50">
...
...
...
</Grid>
</UserControl>
Is the binding correct here or do I need to bind differently? Why is the view not showing up inside the first tab?
you need to connect view model with correct view via DataTemplate.
DataTemplate provides visual representation for data type which doesn't have it (your view model). If you don't specify DataTemplate, you will get default one: TextBlock with string representation of object (result of ToString() method, default to type name).
<Grid>
<Grid.Resources>
<DataTemplate DataType="{x:Type vm:DachdefinitionViewModel}">
<views:Dachdefinition />
</DataTemplate>
</Grid.Resources>
<TabControl Style="{DynamicResource TabControlStyle}"
ItemsSource="{Binding TabCollection}" >
<TabControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</TabControl.ItemTemplate>
<TabControl.ContentTemplate>
<DataTemplate>
<UserControl>
<ContentControl Content="{Binding VM}" />
</UserControl>
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
</Grid>
Your TabControl declaration should look like this:
<TabControl ItemsSource="{Binding TabCollection}">
<TabControl.Resources>
<DataTemplate DataType="{x:Type vm:DachdefinitionViewModel}">
<local:Dachdefinition/>
</DataTemplate>
</TabControl.Resources>
<TabControl.ItemContainerStyle>
<Style TargetType="TabItem">
<Setter Property="Header" Value="{Binding Name}"/>
<Setter Property="Content" Value="{Binding VM}"/>
</Style>
</TabControl.ItemContainerStyle>
</TabControl>
And the Dachdefinition UserControl must not set its own DataContext property, because the DataContext value is supposed to be inherit from the control's parent element, i.e. the TabItem.
<UserControl x:Class="LuxUs.Views.Dachdefinition" ...>
<!--
do not set UserControl.DataContext here
-->
<Grid Margin="50">
...
</Grid>
</UserControl>
Yes there is a problem in databinding.
at
<ContentControl Content="{Binding VM}" />
This line would just display ToString() value of the object bound to
it. (VM in this case).
Instead you can try using ContentTemplateSelection where you can choose the type of ContentTemplate in run time based on the type of object bound to it.
class TabContentTemplateSelector:DataTemplateSelector
{
public DataTemplate DefaultTemplate { get; set; }
public DataTemplate DachdeTemplate { get; set; }
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
if (item is TabViewModel tabViewModel)
{
if (tabViewModel.VM != null && tabViewModel.VM is DachdefinitionViewModel)
{
return DachdeTemplate;
}
else
{
return DefaultTemplate;
}
}
return base.SelectTemplate(item, container);
}
}
<DataTemplate x:Key="DachdeTemplate">
</DataTemplate>
<DataTemplate x:Key="SomeOtherTemplate">
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
<local:TabContentTemplateSelector x:Key="myTabContentTemplateSelector"
DachdeTemplate="{StaticResource DachdeTemplate}"
DefaultTemplate="{StaticResource
SomeOtherTemplate}"
/>
</UserControl.Resources>
<Grid>
<TabControl ItemsSource="{Binding TabCollection}"
ContentTemplateSelector="{StaticResource
myTabContentTemplateSelector}" >
<TabControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</TabControl.ItemTemplate>
</TabControl>
</Grid>
https://www.c-sharpcorner.com/UploadFile/41e70f/dynamically-selecting-datatemplate-for-wpf-listview-way-1/
Check this for how to dynamically change template.. In the template you can use any kind of user control.

Lookless Control's ItemTemplatePanel Not Able to See Dependency Property on Control

So when I use the below style, it is applied to my control as expected. However, the templates inside of the GridView (ItemsPanelTemplate and ItemsTemplate) look at the view model the consumer applies for its data context.
The problem is that I want to set the item dimensions in my control.
So my question is, how do I apply the control template as the data context to the ItemsPanelTemplate and the ItemTemplate?
My first thought was to use ancestral binding but that doesn't appear to be a feature in UWP.
My Control Class
public class FilterableImageWrapGrid : FilterableContentList
{
private GridView _partGridView;
public Point ItemDimensions
{
get { return (Point)GetValue(ItemDimensionsProperty); }
set { SetValue(ItemDimensionsProperty, value); }
}
// Using a DependencyProperty as the backing store for ItemDimensions. This enables animation, styling, binding, etc...
public static readonly DependencyProperty ItemDimensionsProperty =
DependencyProperty.Register("ItemDimensions", typeof(Point), typeof(FilterableImageWrapGrid), new PropertyMetadata(new Point()));
public FilterableImageWrapGrid()
{
DefaultStyleKey = typeof(FilterableImageWrapGrid);
}
protected override void OnApplyTemplate()
{
_partGridView = GetTemplateChild("PART_FilterableImageList") as GridView;
base.OnApplyTemplate();
}
private static void OnItemDimensionsChanged(object sender, DependencyPropertyChangedEventArgs args)
{
FilterableImageWrapGrid wrapGrid = sender as FilterableImageWrapGrid;
if (wrapGrid != null && wrapGrid._partGridView != null)
{
wrapGrid._partGridView.ItemTemplate.SetValue(GridViewItem.WidthProperty, wrapGrid.ItemDimensions.X);
wrapGrid._partGridView.ItemTemplate.SetValue(GridViewItem.HeightProperty, wrapGrid.ItemDimensions.Y);
}
}
}
My style in my Generic.xaml file
<Style TargetType="controls:FilterableImageWrapGrid">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Grid VerticalAlignment="Stretch">
<GridView
x:Name="PART_FilterableImageList"
ItemsSource="{Binding RelativeSource={RelativeSource Mode=TemplatedParent}, Path=FilteredItems, Mode=TwoWay}"
SelectedItem="{Binding RelativeSource={RelativeSource Mode=TemplatedParent}, Path=SelectedContentItem, Mode=TwoWay}">
<GridView.ItemContainerTransitions>
<TransitionCollection>
<EntranceThemeTransition IsStaggeringEnabled="True"/>
<AddDeleteThemeTransition />
<EdgeUIThemeTransition Edge="Left"/>
</TransitionCollection>
</GridView.ItemContainerTransitions>
<GridView.ItemsPanel>
<ItemsPanelTemplate>
<ItemsWrapGrid
x:Name="PART_ItemsWrapGrid"
ItemHeight="{Binding RelativeSource={RelativeSource Mode=TemplatedParent}, Path=ItemDimensions.Y}"
ItemWidth="{Binding RelativeSource={RelativeSource Mode=TemplatedParent}, Path=ItemDimensions.X}"
Margin="2" Orientation="Horizontal"
HorizontalAlignment="Center"/>
</ItemsPanelTemplate>
</GridView.ItemsPanel>
<GridView.ItemTemplate>
<DataTemplate>
.... Data template that binds to the view model the consumer provides....
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
If I understand you correctly it doesn't work to have the RelativeSource Mode=TemplatedParent binding in a template inside a template. Is that it?
then define the ItemDimensions property as an attached Dependency Property:
public class FilterableImageWrapGrid : FilterableContentList
public static Point GetItemDimensions(DependencyObject obj)
{
return (Point)obj.GetValue(ItemDimensionsProperty);
}
public static void SetItemDimensions(DependencyObject obj, Point value)
{
obj.SetValue(ItemDimensionsProperty, value);
}
public static readonly DependencyProperty ItemDimensionsProperty =
DependencyProperty.RegisterAttached("ItemDimensions", typeof(Point), typeof(ItemsWrapGrid), new PropertyMetadata(new Point()));
...
}
and then add this to the template:
<GridView
x:Name="PART_FilterableImageList"
...
<GridView.ItemsPanel>
<ItemsPanelTemplate>
<ItemsWrapGrid
x:Name="PART_ItemsWrapGrid"
ItemHeight="{Binding RelativeSource=
{RelativeSource Mode=Self}, Path=ItemDimensions.Y}"
ItemWidth="{Binding RelativeSource=
{RelativeSource Mode=Self}, Path=ItemDimensions.X}"
Margin="2" Orientation="Horizontal"
HorizontalAlignment="Center"/>
</ItemsPanelTemplate>
</GridView.ItemsPanel>
...
</GridView>
That would be like an inheritable property (which don't exist in uwp (yet?)) that you manually push downward the visual tree to the inner template with the template binding.

Binding from a property of each item inside an ItemsControl to a property of an object outside the ItemsControl

I have an ItemsControl, and a Button outside the ItemsControl. Each item inside the ItemsControl has a dependency property called "MyProperty" (defined in the code-behind).
I would like to set the IsEnabled property of the Button to false when at least one of the items in the ItemsControl has the MyProperty property set to 5. (of course this is just a stupid example of a more complicated situation)
I tried by means of a data trigger, but with no luck:
XAML:
<Window x:Class="cancellami24.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>
<Style x:Key="MyStyle" TargetType="{x:Type ContentPresenter}">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=MyProperty}" Value="5">
<Setter Property="IsEnabled" TargetName="MyButton" Value="False" /><!--error on TargetName-->
</DataTrigger>
</Style.Triggers>
</Style>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<ItemsControl x:Name="MyListBox" Grid.Row="0" ItemContainerStyle="{StaticResource MyStyle}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=MyProperty, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<Button x:Name="MyButton" Grid.Row="1" Click="MyButton_Click"/>
</Grid>
</Window>
Code-behind:
using System.Collections.ObjectModel;
using System.Windows;
namespace cancellami24
{
public partial class MainWindow : Window
{
private readonly ObservableCollection<MyItem> myCollection = new ObservableCollection<MyItem>();
public MainWindow()
{
InitializeComponent();
myCollection.Add(new MyItem(1));
myCollection.Add(new MyItem(2));
myCollection.Add(new MyItem(3));
MyListBox.ItemsSource = myCollection;
}
private void MyButton_Click(object sender, RoutedEventArgs e)
{
myCollection[2].SetValue(MyItem.MyPropertyProperty, 5);
}
}
public class MyItem : DependencyObject
{
public static readonly DependencyProperty MyPropertyProperty = DependencyProperty.Register("MyProperty", typeof(int), typeof(MyItem));
public MyItem(int propertyValue)
{
SetValue(MyPropertyProperty, propertyValue);
}
}
}
You need custom converter to solve it
public class MyConverter : IValueConverter
{
bool flag = false;
var collection = value as ObservableCollection<MyItem>();
if(collection==null) return flag;
foreach (var item in collection)
{
if (item.MyProperty==5)
{
flag = true;
break;
}
}
return flag;
}
Add MyConverter to your App.xaml
<local:MyConverter x:key="MyConverter"/>
Xaml:
<Button x:Name="MyButton" IsEnabled="{Binding ElementName=MyListBox, Path=ItemsSource, Converter={StaticResource MyConverter}}"/>

How to bind an element defined inside the control template for a custom control to a property defined in a subclass (of custom control class)

I would like to bind an element inside a control template for a custom control to a property defined in a child class defined inside the custom control class. What might be the syntax for doing that (see {Binding ???})?
Some code...
C# code:
public class CustmCntrl : Control
{
// blablabla
public class SubChildClass: INotifyPropertyChanged
{
public double X { get; private set; }
public string info { get; private set; }
}
}
XAML:
<Style TargetType="{x:Type local:CustmCntrl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:CustmCntrl}">
<Grid> ... </Grid>
<ItemsControl
ItemsSource="{Binding stuffToDisplay, RelativeSource={RelativeSource TemplatedParent}}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate >
<Grid> ... </Grid>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<local:X
ToolTip="{Binding info ???}">
<local:X.RenderTransform>
<TranslateTransform X="{Binding X ???}"/>
</local:X.RenderTransform>
</local:X>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
I can't test this at the moment, but you should be able to bind by adding the name of the SubChildClass class. Try something like this:
<TextBlock Text="{Binding SubChildClass.PropertyName, RelativeSource={RelativeSource
AncestorType={x:Type YourPrefix:YourCustomControl}}}">
If that doesn't work, try this:
<TextBlock Text="{Binding (SubChildClass.PropertyName), RelativeSource={RelativeSource
AncestorType={x:Type YourPrefix:YourCustomControl}}}">
You can find out more from the Property Path Syntax page on MSDN.
UPDATE >>>
Yeah, after getting a chance to test this out in a project, it seems that you can't data bind directly with class properties like that. However, if you just wanted to declare the class there as a container for some basic data items in your control then that is fine. As long as you define some DependencyPropertys to hold them, you can use that class just fine:
private static DependencyProperty ItemsProperty = DependencyProperty.Register("Items",
typeof(ObservableCollection<SubChildClass>), typeof(CustomControl1));
public ObservableCollection<SubChildClass> Items
{
get { return (ObservableCollection<SubChildClass>)GetValue(ItemsProperty); }
set { SetValue(ItemsProperty, value); }
}
In Generic.xaml:
<ListBox ItemsSource="{Binding Items,
RelativeSource={RelativeSource AncestorType={x:Type local:CustmCntrl}}}" />

Categories