I understand that interesting things happen to attached properties in datatemplates but this one is very strange.
I have a behavior with a dependency property on it, the property is type List<DataStatePair>
[System.Windows.Markup.ContentProperty("StateDefinitions")]
public class MultiDataStateBehavior: StateBehaviourBase
{
public List<DataStatePair> StateDefinitions
{
get { return (List<DataStatePair>)GetValue(StateDefinitionsProperty); }
set { SetValue(StateDefinitionsProperty, value); }
}
// Using a DependencyProperty as the backing store for StateDefinitions. This enables animation, styling, binding, etc...
public static readonly DependencyProperty StateDefinitionsProperty =
DependencyProperty.Register("StateDefinitions", typeof(List<DataStatePair>), typeof(MultiDataStateBehavior), new PropertyMetadata(new List<DataStatePair>()));
}
As you can see, I've marked it as the content property. The XAML looks like this:
<DataTemplate>
<!-- VISUAL STATES OMITTED FOR BREVITY-->
<Grid x:Name="grid" Background="Transparent" ContextMenu="{StaticResource ContextMenu_ToolMenu}">
<i:Interaction.Behaviors>
<ext:MultiDataStateBehavior Binding="{Binding Type}">
<ext:DataStatePair State="None" Value="{x:Null}"/>
<ext:DataStatePair State="Gauge" Value="{x:Static jcm:ToolType.Gauge}"/>
<ext:DataStatePair State="Repeater" Value="{x:Static jcm:ToolType.Gauge}"/>
</ext:MultiDataStateBehavior>
</i:Interaction.Behaviors>
</Grid>
</DataTemplate>
The problem? 3 DataStatePair instances are added for each use of the datatemplate. I use the template 32 times in my app and get 96 DataStatePair instances in total. Grizzly! I understand how this is possible. The Behavior is static for the datatemplate but the DataStatePair instances are not and a List can be added to.
If change the dependency property to an IEnumerable everything breaks - it will not compile. If I set the property explicitly with an x:Array in XAML, everything works as expected - I only ever get 3 states. XAML below;
<i:Interaction.Behaviors>
<ext:MultiDataStateBehavior Binding="{Binding Type}" UseTransitionsOnLoad="True">
<ext:MultiDataStateBehavior.StateDefinitions>
<x:Array Type="{x:Type ext:DataStatePair}">
<ext:DataStatePair State="None" Value="{x:Null}"/>
<ext:DataStatePair State="Gauge" Value="{x:Static jcm:ToolType.Gauge}"/>
<ext:DataStatePair State="Repeater" Value="{x:Static jcm:ToolType.Gauge}"/>
</x:Array>
</ext:MultiDataStateBehavior.StateDefinitions>
</ext:MultiDataStateBehavior>
</i:Interaction.Behaviors>
Does anyone know why this is and what the most elegant solution is. I can imagine a Microsoft implementation would not make you use x:Array.
EDIT : The x:Array solution breaks the blend designer.
XamlParseException: Add value to collection of type
'System.Collections.Generic.IEnumerable(SSW.WPFExtensions.DataStatePair)'
threw an exception.
EDIT : Removing the [System.Windows.Markup.ContentProperty("StateDefinitions")] attribute definition works great. I dont understand what is going on!
WPF, what are you doing. WPF, STAHP
Potential solution...and this is a doozy.
Microsoft provides guidance for creating dependency properties that are collections
here.
This documentation specifies that you should never declare the default value of the property as an instance but initialise the collection in the owning class' constructor and set the dependency property. eg.
public Aquarium() : base()
{
SetValue(AquariumContentsPropertyKey, new List<FrameworkElement>());
}
...[the] single list default
value is shared for all instances of Aquarium. If you ran the
following test code, which is intended to show how you would
instantiate two separate Aquarium instances and add a single different
Fish to each of them, you would see a surprising result:
As for my design time exceptions. Same problem expect with new DataStatePair[0] which is immutable, terrible error reporting.
Conclusion - Someone at Microsoft is having a good chuckle at my expense.
Related
To familiarize myself with WPF and MVVM concepts I built a visual representation of a Sudoku board.
My (simplified) setup looks like this (no custom code-behind in views anywhere):
I have a MainWindow.xaml:
<Window x:Class="Sudoku.WPF.MainWindow">
<Window.DataContext>
<models:MainWindowViewModel/>
</Window.DataContext>
<ctrl:SudokuBoard DataContext="{Binding Path=GameViewModel}"/>
</Window>
My MainWindowViewModel:
class MainWindowViewModel
{
public MainWindowViewModel()
{
IGame g = new Game(4);
this.GameViewModel = new GameViewModel(g);
}
public IGameViewModel GameViewModel { get; private set; }
}
SudokuBoard is a UserControl. Its DataContext is set to GameViewModel as per above.
Relevant parts of GameViewModel, Elements is populated in the ctor, Possibilities is set via a command:
public IList<CellViewModel> Elements { get; private set; }
private bool _showPossibilities;
public bool ShowPossibilities
{
get { return _showPossibilities; }
set
{
_showPossibilities = value;
OnPropertyChanged();
}
}
In SudokuBoard.xaml I have:
<ItemsControl x:Name="SudokuGrid" ItemsSource="{Binding Path=Elements}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<ContentControl Style="{StaticResource ToggleContentStyle}"
Content="{Binding}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Elements is a collection of CellViewModels generated in the constructor of GameViewModel.
Now to the question: my ToggleContentStyle as defined in <UserControl.Resources>:
<Style x:Key="ToggleContentStyle" TargetType="{x:Type ContentControl}">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=DataContext.ShowPossibilities, ElementName=SudokuGrid}" Value="False">
<Setter Property="ContentTemplate" Value="{StaticResource valueTemplate}"/>
</DataTrigger>
<DataTrigger Binding="{Binding Path=DataContext.ShowPossibilities, ElementName=SudokuGrid}" Value="True">
<Setter Property="ContentTemplate" Value="{StaticResource possibilityTemplate}" />
</DataTrigger>
</Style.Triggers>
</Style>
(both ContentTemplates just show other properties of a single CellViewModel in different representations)
Question 1: I have to explicitly reference DataContext in order to get to the ShowPossibilities property. If I leave it out, so that Path=ShowPossibilities, I get a UniformGrid with the ToString() representation of CellViewModel. My assumption is that that is because the style is referenced from the ItemTemplate, with it's binding set to a single CellViewModel. Is that assumption valid?
Question 2: When I omit the ElementName part, I also get the ToString() representation of CellViewModel. Now I'm really confused. Why is it needed?
Datacontext is a dependency property which is marked as inherits. That means its inherited down the visual tree.
When you bind the default place it's going to look for a source is in the datacontext.
This is the simple situation.
Say you have a window and that has datacontext set to WindowViewmodel and stick a textbox in that Window. You bind it's Text to FooText. This means the textbox goes and looks for a FooText property in that instance of WindowViewmodel.
All pretty simple so far.
Next...
You use elementname.
What that does is says go and take a look at this element. Look for a property on that. If you did that with our textbox above then it would expect a dependency property FooText on whatever you point it to.
Datacontext is a dependency property.
And when you do:
"{Binding FooProperty
This is shorthand for:
"{Binding Path=FooProperty
Where FooProperty is a property path, not =just the name of a property.
Which is maybe worth googling but means you can use "dot notation" to walk down the object graph and grab a property on an object ( on an object.... ).
Hence DataContext.Foo or Tag.Whatever ( since tag is another dependency property a control will have ).
Let's move on to some other complications.
The datcontext is inherited down the visual tree but there's a few of gotchas here. Since
some things look like they're controls but are not ( like datagridtextcolumn ). Templated things can be tricky. Itemscontrols are a kind of obvious and relevent special case.
For an itemscontrol, the datacontext of anything in each row is whichever item it's presented to from the itemssource. Usually you're binding an observablecollection of rowviewmodel to that itemssource. Hence ( kind of obviously ) a listbox or datagrid shows you the data from each rowviewmodel you gave it in each row.
If you then want to go get a property is not in that rowviewmodel you need to tell it to look somewhere else.
When you specify an element in Binding (eg ElementName=SudokuGrid), the Path has to refer to any property of that element. Because this element is a wpf control, DataContext is one of it's properties but ShowPossibilities isn't. So if you do just Path=ShowPossibilities it will not be able to find that path at all.
If you don't specify element in Binding at all then it defaults to the DataContext associated with the control. If the associated DataContext doesn't have the property ShowPossibilities it will not be able to find it.
PS: If you want to debug wpf UI to see what the DataContext is at run-time you could use utility like Snoop.
imagine the following simple Models (example for simplicity reasons; in fact, we have MVVM here but it doesn't matter):
public class User {
public string Username { get; set; }
}
public class StackOverflowUser : User {
public int Reputation { get; set; }
}
Now we have a Silverlight UserControl which contains the following Controls (again, this is just an example, stripped down to the core):
<Grid>
<TextBlock Text="Username:" />
<TextBlock Text="{Binding Path=Username}" />
<TextBlock Text="Reputation:" />
<TextBlock Text="{Binding Path=Reputation}" />
</Grid>
Now I'd like this UserControl to be compatible with both Models, User and StackOverflowUser. I might set the UserControl's DataContext to either a User or StackOverflowUser Type:
this.DataContext = new User { Username = "john.doe" };
If set to StackOverflowUser, everything works fine. If set to User, I'm getting a "BindingExpression Path error", because the Property Reputation is missing in the User Model. Which I understand completely.
Is there any way to 1) avoid this
exception and 2) control the
visibility of the controls, collapse
when bound property is not available?
Of course, we prefer an elegant solution, where the problem is solved by tuning the Binding Expression and/or using Converters etc. and avoid tons of code behind if possible.
Thanks in advance for your help and suggestions,
best regards,
Thomas
Unfortunately Silverlight is limited in its polymorphic behavior regarding DataTemplates, I can only think of a workaround:
Give the User class the property Reputation too, but make it meaningless, for example -1. Then apply a style to the reputation TextBlocks:
<Page.Resources>
<Style Key="Reputation">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=Reputation} Value="-1">
<Setter Property="Visibility" Value="Invisible" />
</DataTrigger>
</Style.Triggers>
</Style>
</Page.Resources>
...
<TextBlock Text="Reputation:" Style="{StaticResource Reputation}">
<TextBlock Text="{Binding Path=Reputation}" Style="{StaticResource Reputation}">
You could also try (I can not test this):
giving the User class a new property that identifies its type,
make a second Style for the second TextBlock
bind its DataTrigger to the type identifying property and move the {Binding Path=Reputation} declaration into a Setter:
<Style Key="ReputationContent">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=Type} Value="StackOverflow">
<Setter Property="Visibility" Value="Invisible" />
<Setter Property="Text" Value="{Binding Path=Reputation}" />
</DataTrigger>
</Style.Triggers>
</Style>
But you see, there is no elegant way, it's a shame that DataTemplate do not have a DataType property in Silverlight.
You mentioned you're using MVVM. This is the value of your viewmodel - to shape model data in preparation for the view. The viewmodel could have accessible properties for both username and reputation (and maybe even another bool for binding the visibility). The viewmodel would include all logic on how to fill those properties from either model (User or StackOverflowUser). The view would have no knowledge of a User or StackOverflowUser object, just the viewmodel.
I finally got my problem solved. A co-worker finally implemented a solution including a workaround for WPFs DataTemplates DataType attribute (or generally, a DataTemplateSelector). It's not very pretty (i guess, no workaround is) but it works. Unfortunately, i cannot post any code snippets because its closed-source. But i found some links afterwards, providing a pretty similar solution, like this one: Silverlight: a port of the DataTemplateSelector. If you have a similar problem, this will help you as well. Here or there are more thoughts on this subject.
The actual solution is following Ozan's hints. Unfortunately, his solution is not working so I don't want to mark his comment as the accepted answer but I give at least an upvote.
Thanks!
best regards,
Thomas
I know this has already been answered, but I still think its worth this post. Using reflection you can have a property in your ViewModel that will easily handle Dto objects which only sometimes have the property. Reflection can be expensive though, so weigh that with your decision.
public int? Reputation
{
get
{
var prop = Dto.GetType().GetProperty("Reputation");
return (prop != null)? (int)prop.GetValue(Dto, null) : null;
}
set
{
var prop = Dto.GetType().GetProperty("Reputation");
if(prop !=null) prop.SetValue(Dto,value, null);
}
}
In WPF, what, really, does it mean to be a "dependency property"?
I read Microsoft's Dependency Properties Overview, but it's not really sinking in for me. In part that article says:
Styles and templates are two of the chief motivating scenarios for using dependency properties. Styles are particularly useful for setting properties that define application user interface (UI). Styles are typically defined as resources in XAML. Styles interact with the property system because they typically contain "setters" for particular properties, as well as "triggers" that change a property value based on the real-time value for another property.
And then the example code is this:
<Style x:Key="GreenButtonStyle">
<Setter Property="Control.Background" Value="Green"/>
</Style>
....
<Button Style="{StaticResource GreenButtonStyle}">I am green!</Button>
But I'm not getting what is special about this. Does it just imply, that when I set Style on the button to the given style, that I am actually setting Background implicitly? Is that the crux of it?
Here's the explanation for how dependency properties work that I always wished someone had written for me. It's incomplete and quite possibly wrong, but it will help you develop enough of an understanding of them that you can will be able to grasp the documentation that you read.
Dependency properties are property-like values that are get and set via methods of the DependencyObject class. They can (and generally do) look very much like CLR properties, but they're not. And this gets to the first confusing thing about them. A dependency property is really made up of a couple of components.
Here's an example:
Document is a property of the RichTextBox object. It's a real CLR property. That is to say, it's got a name, a type, a getter, and a setter, just like any other CLR property. But unlike "normal" properties, the RichTextBox property doesn't merely get and set a private value inside the instance. Internally, it's implemented like this:
public FlowDocument Document
{
get { return (FlowDocument)GetValue(DocumentProperty); }
set { SetValue(DocumentProperty, value); }
}
When you set Document, the value you passed in gets passed to SetValue, along with DocumentProperty. And what is that? And how does GetValue get its value? And ...why?
First the what. There's a static property defined on the RichTextBox named DocumentProperty. When this property is declared, it's done like this:
public static DependencyProperty DocumentProperty = DependencyProperty.Register(
"Document",
typeof(FlowDocument),
typeof(RichTextBox));
The Register method, in this case, tells the dependency property system that RichTextBox - the type, not the instance - now has a dependency property named Document of type FlowDocument. This method stores this information...somewhere. Where, exactly, is an implementation detail that's hidden from us.
When the setter for the Document property calls SetValue, the SetValue method looks at the DocumentProperty argument, verifies that it's really a property that belongs to RichTextBox and that value is the right type, and then stores its new value...somewhere. The documentation for DependencyObject is coy on this implementation detail, because you don't really need to know it. In my mental model of how this stuff works, I assume there's a property of type Dictionary<DependencyProperty, object> that's private to the DependencyObject, so derived classes (like RichTextBox) can't see it but GetValue and SetValue can update it. But who knows, maybe it's written on parchment by monks.
At any rate, this value is now what's called a "local value," which is to say it's a value that's local to this specific RichTextBox, just like an ordinary property.
The point of all this is:
CLR code doesn't need to know that a property is a dependency property. It looks exactly like any other property. You can call GetValue and SetValue to get and set it, but unless you're doing something with the dependency property system, you probably don't need to.
Unlike a normal property, something other than the object that it belongs to can be involved in getting and setting it. (You could do this with reflection, conceivably, but reflection is slow. Looking things up in dictionaries is fast.)
This something - which is the dependency property system - essentially sits between an object and its dependency properties. And it can do all kinds of things.
What kinds of things? Well, let's look at some use cases.
Binding. When you bind to a property, it has to be a dependency property. This is because the Binding object doesn't actually set properties on the target, it calls SetValue on the target object.
Styles. When you set an object's dependency property to a new value, SetValue tells the style system that you've done so. That's how triggers work: they don't find out that a property's value has changed through magic, the dependency property system tells them.
Dynamic resources. If you write XAML like Background={DynamicResource MyBackground}, you can change the value of the MyBackground resource, and the background of the object referencing it gets updated. This isn't magic either; the dynamic resource calls SetValue.
Animations. Animations work by manipulating property values. Those have to be dependency properties, because the animation is calling SetValue to get at them.
Change notification. When you register a dependency property, you can also specify a function that SetValue will call when it sets the property's value.
Value inheritance. When you register a dependency property, you can specify that it participate in property value inheritance. When you call GetValue to get the value of an object's dependency property, GetValue looks to see if there's a local value. If there's not, it traverses up the chain of parent objects looking at their local values for that property.
This is how it is that you can set the FontFamily on a Window and magically (I'm using that word a lot) every control in the window uses the new font. Also, it's how it is that you can have hundreds of controls in a window without each of them having a FontFamily member variable to track their font (since they don't have local values) but you can still set the FontFamily on any one control (because of the seekrit hidden dictionary of values that every DependencyObject has).
In WPF, what, really, does it mean to be a "dependency property"?
In order to be a dependency property, the property must actually be defined as a DependencyProperty, statically, on the class. The dependency property system is very different than a standard CLR property.
Dependency properties are handled very differently, though. A type defines a dependency property statically, and provides a default value. The runtime actually doesn't generate a value for an instance until it's needed. This provides one benefit - the property doesn't exist until requested for a type, so you can have a large number of properties without overhead.
This is what makes the styling work property, but is also important to allow attached properties, property "inheritance" through the visual tree, and many other things WPF relies on.
For example, take the DataContext dependency property. Typically, you set the DataContext dependency property for a Window or a UserControl. All of the controls within that Window, by default, "inherit" their parent's DataContext proeprty automatically, which allows you to specify data bindings for controls. With a standard CLR property, you'd need to define that DataContext for every control in the window, just to get binding to work properly.
It may be helpful to understand what problem the dependency property is trying to solve.
If we put the Binding, Animation and the Change Event model to one side as they've been discussed in other answers, the benefit is memory usage and thus scalability to host many thousand WPF objects in a window.
If a window contains 1000 Label objects with each Label object having the usual Foreground, Background, FontFamily, FontSize, FontWeight, etc., then traditionally this would consume memory because each property would have a private backing field to store the value.
Most applications will change only a few properties, the majority of which will be left at their default values. Basically very wasteful and redundant information (each object just holding the same default values in memory)
This is where dependency properties are different.
// Lets register the Dependency Property with a default value of 20.5
public static readonly DependencyProperty ColumnWidthProperty =
DependencyProperty.Register("ColumnWidth", typeof(double), typeof(MyWPFControl), new UIPropertyMetadata(20.5, ColWitdhPropChanged));
public double ColumnWidth
{
get { return (double)GetValue(ColumnWidthProperty); }
set { SetValue(ColumnWidthProperty, value); }
}
There is no private backing field. When the dependency property is registered a default value can be specified. So in most cases the returned value from GetValue is the default value that has only been stored the once to cover all instances of the Label object across all windows of your application.
When a dependency property is set using the SetValue it stores the non-default value in a collection identified by the object instance, to be returned in all subsequent GetValue calls.
This storage method will therefore only consume memory for the properties of the WPF objects that have changed from the default value. i.e. only the differences from the default value.
A simple/fundamental difference - Change Notification: Changes to Dependency Properties are reflected/refreshed in UI on changes whereas CLR properties don't.
<Window x:Class="SampleWPF.MainWindow"
x:Name="MainForm"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SampleWPF"
Title="About WPF Unleashed" SizeToContent="WidthAndHeight"
Background="OrangeRed"
>
<StackPanel DataContext="{Binding ElementName=MainForm}">
<!-- Bind to Dependency Property -->
<Label Name="txtCount1" FontWeight="Bold" FontSize="20" Content="{Binding ElementName=MainForm, Path=Count1, Mode=OneWay}" />
<!-- Bind to CLR Property -->
<Label Name="txtCount2" Content="{Binding ElementName=MainForm, Path=Count2, Mode=OneWay}"></Label>
<!-- Bind to Dependency Property (Using DataContext declared in StackPanel) -->
<Label Name="txtCount3" FontWeight="Bold" FontSize="20" Content="{Binding Count1}" />
<!-- Child Control binding to Dependency Property (Which propagates down element tree) -->
<local:UserControl1 />
<!-- Child Control binding to CLR Property (Won't work as CLR properties don't propagate down element tree) -->
<local:UserControl2 />
<TextBox Text="{Binding ElementName=txtCount1, Path=Content}" ></TextBox>
<TextBox Text="{Binding ElementName=txtCount2, Path=Content}" ></TextBox>
<Button Name="btnButton1" Click="btnButton1_Click_1">Increment1</Button>
<Button Name="btnButton2" Click="btnButton1_Click_2">Increment2</Button>
</StackPanel>
</Window>
<UserControl x:Class="SampleWPF.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">
<StackPanel>
<Label Content="{Binding Count1}" ></Label>
<!--
<Label Content="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=Count1}"></Label>
-->
</StackPanel>
</UserControl>
<UserControl x:Class="SampleWPF.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"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<StackPanel>
<Label Content="{Binding Count2}" ></Label>
<!--
<Label Content="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=Count2}"></Label>
-->
</StackPanel>
</UserControl>
And the code behind here (To declare the CLR and Dependency property):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace SampleWPF
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public static readonly DependencyProperty Count1Property;
private int _Count2 = 2;
public int Count2
{
get { return _Count2; }
set { _Count2 = value; }
}
public MainWindow()
{
return;
}
static MainWindow()
{
// Register the property
MainWindow.Count1Property =
DependencyProperty.Register("Count1",
typeof(int), typeof(MainWindow),
new FrameworkPropertyMetadata(1,
new PropertyChangedCallback(OnCount1Changed)));
}
// A .NET property wrapper (optional)
public int Count1
{
get { return (int)GetValue(MainWindow.Count1Property); }
set { SetValue(MainWindow.Count1Property, value); }
}
// A property changed callback (optional)
private static void OnCount1Changed(
DependencyObject o, DependencyPropertyChangedEventArgs e) {
}
private void btnButton1_Click_1(object sender, RoutedEventArgs e)
{
Count1++;
}
private void btnButton1_Click_2(object sender, RoutedEventArgs e)
{
Count2++;
}
}
}
Another feature provided by Dependency Properties is value inheritance - value set in top level elements propagates down the element tree - In following example taken from http://en.csharp-online.net, FontSize and FontStyle declared on "Window" tag is applied to all child elements underneath:
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Title="About WPF Unleashed" SizeToContent="WidthAndHeight"
FontSize="30" FontStyle="Italic"
Background="OrangeRed">
<StackPanel>
<Label FontWeight="Bold" FontSize="20" Foreground="White">
WPF Unleashed (Version 3.0)
</Label>
<Label>© 2006 SAMS Publishing</Label>
<Label>Installed Chapters:</Label>
<ListBox>
<ListBoxItem>Chapter 1</ListBoxItem>
<ListBoxItem>Chapter 2</ListBoxItem>
</ListBox>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
<Button MinWidth="75" Margin="10">Help</Button>
<Button MinWidth="75" Margin="10">OK</Button>
</StackPanel>
<StatusBar>You have successfully registered this product.</StatusBar>
</StackPanel>
</Window>
References:
http://www.codeproject.com/Articles/29054/WPF-Data-Binding-Part-1
http://en.csharp-online.net/WPF_Concepts%E2%80%94Property_Value_Inheritance
This is a situation that comes up often:
In the View, you have a control bound to a ViewModel property (backed by a INotifyPropertyChanged). For example:
<TextBlock Text="{Binding Path=Subtotal}"/>
When the property changes, you need to bring the user attention to the fact with some creative animation. How I can utilize the fact that the view is already wired to the notification and avoid creating much of the extra code (or at least create it once and re-use). Data triggers are probably the best choice, but I do not know how to make them fire on any value change versus on some specific value.
The following options come to mind:
raise an additional event in the ViewModel, subscribe in the View code-behind.
create a datatrigger bound to the property mentioned using a convertor that would return true if the value is changing.
create a datatrigger bound to a new boolean property on the ViewModel which is used to "signal" the change.
create a behavior attached to the control which would subscribe to the control's dependency property change and start the animation.
Which one do you like/use? Did I miss any options?
P.S. It would be nice (but not critical) if the solution would provide a possibility to start the animation first and reflect the value change when it is ended.
Ok, this is what I came to after some experimenting.
I have created an Expression Blend 3 trigger with a dependency property (I named it Subscription). I bind the Subscription to the same value that my TextBlock is bound to and this trigger is attached to a ControlStoryboardAction from Expression Blend 3.
Here's the trigger:
public class DataTriggerPlus : TriggerBase<DependencyObject>
{
public static readonly DependencyProperty SubscriptionProperty =
DependencyProperty.Register("Subscription",
typeof(string),
typeof(DataTriggerPlus),
new FrameworkPropertyMetadata("",
new PropertyChangedCallback(OnSubscriptionChanged)));
public string Subscription
{
get { return (string)GetValue(SubscriptionProperty); }
set { SetValue(SubscriptionProperty, value); }
}
private static void OnSubscriptionChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
((DataTriggerPlus)d).InvokeActions(null);
}
}
Here's how it is attached to the storyboard:
<TextBlock x:Name="textBlock" Text="{Binding TestProp}" Background="White">
<i:Interaction.Triggers>
<local:DataTriggerPlus Subscription="{Binding TestProp}">
<im:ControlStoryboardAction
Storyboard="{StaticResource Storyboard1}"/>
</local:DataTriggerPlus>
</i:Interaction.Triggers>
</TextBlock>
I like this approach a lot, great job Blend 3 designers!
Edit: answering Drew comment...
Yes, it ships with Blend. You can just include Microsoft.Expression.Interactions.dll and System.Windows.Interactivity into your project.
And yes, it is verbose (I have asked if somebody figured out a good way to apply behaviours via Styles in this question) - but there is also a benefit of flexibility. For example you can not only start a storyboard, but also switch a state or do some other action from the same trigger.
You can create a trigger that will start the animation.
Something like this:
<Style>
<Style.Triggers>
<Trigger
Property="ViewModelProperty"
Value="True">
<Trigger.EnterActions>
<BeginStoryboard Storyboard="YourStoryBoard" />
</Trigger.EnterActions>
</Trigger>
</Style.Triggers>
</Style>
As for the issue for the issue of setting the value once the animation has completed, this is a bit of a pain. As far as I'm aware you'd need to use the completed event on the storyboard, this requires code behind, which is something you want to avoid with MVVM.
I've tried using EventTriggers to bind to the completed events, but that also introduces some complications. See here for more details.
I have recently started investigating the MVVM pattern with WPF for an upcoming project. I started with Josh Smith's MSDN article. I have a question (well many, but let's start with one):
I have an IndividualViewModel which exposes the properties of the model. I need two views "Add Individual" and "Edit Individual" which are very similar as you can imagine. What I have done currently is to have 2 subclasses AddIndividualViewModel and EditIndividualViewModel which expose the Add and Edit commands respectively. I also have 2 similary named views that bind to these.
Now this method works and these classes are fairly small anyway, but I'm wondering if it is possible for me to have just the one view model, which exposes both commands. I would still have 2 views which would bind to this same view model, exposing the appropriate command as a button. I'm not quite sure how to do this. In the main window resources I have something like:
<DataTemplate DataType="{x:Type ViewModels:AddIndividualViewModel}">
<Views:AddIndividualView />
</DataTemplate>
With this method of binding you can only have a one-to-one binding, i.e. the same view is always shown for a given view model. Is there a way to automatically switch the view depending on a property on the view model (e.g. IndividualViewModel.Mode). Is there a different approach I should be considering?
Note that the main window has a collection of view models and shows each in tab.
Thank you!
So you need 2 different views based on a property value. One thing to consider is to refactor your presentation code, so instead of the values of a property you could have real subclasses. Then you can use 2 different DataTemplate for each class.
<DataTemplate DataType="{x:Type ViewModels:AddIndividualViewModel}">
<Views:AddIndividualView />
</DataTemplate>
<DataTemplate DataType="{x:Type ViewModels:EditIndividualViewModel}">
<Views:EditIndividualView />
</DataTemplate>
If you think that is an overkill, you could use a trigger and wrap your specific views into a ContentPresenter.
<DataTemplate x:Key="AddIndividualTemplate" DataType="{x:Type ViewModels:IndividualViewModel}">
<Views:AddIndividualView />
</DataTemplate>
<DataTemplate x:Key="EditIndividualTemplate" DataType="{x:Type ViewModels:IndividualViewModel}">
<Views:EditIndividualView />
</DataTemplate>
<DataTemplate DataType="{x:Type ViewModels:IndividualViewModel}">
<ContentPresenter Content="{Binding}">
<ContentPresenter.Style>
<Style TargetType="ContentPresenter">
<Setter Property="ContentTemplate" Value="{StaticResource AddIndividualTemplate}" />
<Style.Triggers>
<DataTrigger Binding="{Binding Mode}" Value="{x:Static ViewModels:IndividualMode.Edit}">
<Setter Property="ContentTemplate" Value="{StaticResource EditIndividualTemplate}" />
</DataTrigger>
</Style.Triggers>
</Style>
</ContentPresenter.Style>
</ContentPresenter>
</DataTemplate>
Thanks for pointing me in the right direction! I am still new with WPF too and learning about all the different possibilities including binding methods. Anyway for anyone interested, here is the solution I arrived at for this particular case:
I decided I wanted to keep the view models separated in two subclasses AddIndividualViewModel and EditIndividualViewModel which only expose commands, rather than trying to manage state in the one class. However I wanted one view so that I'm not duplicating the XAML. I ended up using two DataTemplates and DataTemplateSelector to switch out the action buttons depending on the view model:
<DataTemplate x:Key="addTemplate">
<Button Command="{Binding Path=AddCommand}">Add</Button>
</DataTemplate>
<DataTemplate x:Key="editTemplate">
<Button Command="{Binding Path=UpdateCommand}">Update</Button>
</DataTemplate>
<TemplateSelectors:AddEditTemplateSelector
AddTemplate="{StaticResource addTemplate}"
EditTemplate="{StaticResource editTemplate}"
x:Key="addEditTemplateSelector" />
and a content presenter at the bottom of the form:
<ContentPresenter Content="{Binding}"
ContentTemplateSelector="{StaticResource addEditTemplateSelector}" />
Here is the code for the template selector:
class AddEditTemplateSelector : DataTemplateSelector
{
public DataTemplate AddTemplate { get; set; }
public DataTemplate EditTemplate { get; set; }
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
if (item is AddIndividualViewModel)
{
return AddTemplate;
}
else if (item is EditIndividualViewModel)
{
return EditTemplate;
}
return null;
}
}
This may or may not be how implement the final thing (given the requirements) but it's good to see I have this sort of option available.
There's no reason why you shouldn't be able to achieve that. One way of doing this is to provide some flag in your view model stating whether you're in add mode or in edit mode, and styling your view based on that flag using simple bindings, triggers or template selectors.
For reference you may look at Sacha Barber's DataWrapper class that's part of his Cinch framework (not directly applicable to your case, but it's a good starting point) which wraps data fields in the view model in such a way to support a flag to toggle between read only (view record mode), and read-write (edit record mode). You could apply a similar approach to make the distinction between add and edit.
Basically, instead of having simple properties in your view model, instantiate a data wrapper class which includes a Value property, and a IsAdding property. In your view, you can use bindings, triggers or template selectors to modify templates based on that property.
For this task you do not need any DataTemplateSelector at all.
Derive both EditIndividualVM and AddINdividualVM from IndividualVM.
The Edit- and AddCommands route to a setter property in the IndividualVM.
The setter VM = new AddIndividualVM or VM = new EditIndividualVM depending on which button is pressed.
In xaml you bind in the contentgrid to your VM property like this: