We have an app that uses simple one way binding with a GridView to display some data. Well, now we need to allow the user to change some of that data, so I've been trying to get two way data binding to work in the GridView. So far everything displays correctly, but editing cells in the GridView seems to do nothing at all. What am I messing up? Is two way databinding like this even possible? Should I just start converting everything to use a different control, like maybe a DataGrid?
I wrote a tiny test app that shows my problem. If you try it, you'll see that the property setters never get called after their initialization.
Xaml:
Title="Window1" Height="300" Width="300">
<Grid>
<ListView Name="TestList">
<ListView.View>
<GridView>
<GridViewColumn Header="Strings">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding Path=String, Mode=TwoWay}"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Bools">
<GridViewColumn.CellTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding Path=Bool, Mode=TwoWay}"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
</Grid>
</Window>
And here's the corresponding code:
using System.Collections.Generic;
using System.Windows;
namespace GridViewTextbox
{
public partial class Window1 : Window
{
private List<TestRow> _rows = new List<TestRow>();
public Window1()
{
InitializeComponent();
_rows.Add(new TestRow("a", false));
_rows.Add(new TestRow("b", true));
_rows.Add(new TestRow("c", false));
TestList.ItemsSource = _rows;
TestList.DataContext = _rows;
}
}
public class TestRow : System.Windows.DependencyObject
{
public TestRow(string s, bool b)
{
String = s;
Bool = b;
}
public string String
{
get { return (string)GetValue(StringProperty); }
set { SetValue(StringProperty, value); }
}
// Using a DependencyProperty as the backing store for String. This enables animation, styling, binding, etc...
public static readonly DependencyProperty StringProperty =
DependencyProperty.Register("String", typeof(string), typeof(TestRow), new UIPropertyMetadata(""));
public bool Bool
{
get { return (bool)GetValue(BoolProperty); }
set { SetValue(BoolProperty, value); }
}
// Using a DependencyProperty as the backing store for Bool. This enables animation, styling, binding, etc...
public static readonly DependencyProperty BoolProperty =
DependencyProperty.Register("Bool", typeof(bool), typeof(TestRow), new UIPropertyMetadata(false));
}
}
When you use Dependency Properties, the Setters will not be called by bindings, instead they change the value directly (using SetValue or something similar).
Try adding a PropertyChangedCallback, and set a breakpoint in there to see if the value is changed from the GridView.
public static readonly DependencyProperty BoolProperty =
DependencyProperty.Register("Bool", typeof(bool), typeof(TestRow), new UIPropertyMetadata(false, OnBoolChanged));
private static void OnBoolChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
//this method will be called everytime Bool changes value
}
The property setters will NOT be called from WPF if they are dependency properties. Those are used as CLR conveniences and get called by code which is not aware of DependencyProperty.
The WPF code will do:
yourControl.SetValue(TestRow.StringProperty, someValue);
Not:
yourControl.String = someValue;
You need to hook the DepedencyPropertyChanged event to hear the changes.
Related
I am trying to store some data in XAML and loading it at runtime. For storing my xaml look like this .
<osp:OSPData x:Class="OptisetStore.Model.OSPData"
xmlns:osp="clr-namespace:OptisetStore.Model;assembly=OptisetStore"
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:OptisetStore.Model"
mc:Ignorable="d"
osp:OSPData.Name="OspCollection">
<osp:OSPData.Features>
<osp:Feature LocalName="feature1" x:Name="F1" IsEnabled="True" />
<osp:Feature LocalName="{Binding ElementName=F1, Path=LocalName, Mode=TwoWay}" IsEnabled="{Binding ElementName=F1, Path=IsEnabled, Mode=TwoWay}" />
</osp:OSPData.Features>
OSPData class
public partial class OSPData : DependencyObject
{
public string Name { get; set; }
public OSPData()
{
Features = new ObservableCollection<Feature>();
}
public ObservableCollection<Feature> Features
{
get { return (ObservableCollection<Feature>)GetValue(FeaturesProperty); }
set { SetValue(FeaturesProperty, value); }
}
// Using a DependencyProperty as the backing store for Features. This enables animation, styling, binding, etc...
public static readonly DependencyProperty FeaturesProperty =
DependencyProperty.Register("Features", typeof(ObservableCollection<Feature>), typeof(OSPData), new PropertyMetadata(new ObservableCollection<Feature>()));
}
Feature Class:
public class Feature : DependencyObject
{
public bool IsEnabled
{
get { return (bool)GetValue(IsEnabledProperty); }
set { SetValue(IsEnabledProperty, value); }
}
// Using a DependencyProperty as the backing store for IsEnabled. This enables animation, styling, binding, etc...
public static readonly DependencyProperty IsEnabledProperty =
DependencyProperty.Register("IsEnabled", typeof(bool), typeof(Feature), new PropertyMetadata(false));
public string LocalName
{
get { return (string)GetValue(LocalNameProperty); }
set { SetValue(LocalNameProperty, value); }
}
// Using a DependencyProperty as the backing store for LocalName. This enables animation, styling, binding, etc...
public static readonly DependencyProperty LocalNameProperty =
DependencyProperty.Register("LocalName", typeof(string), typeof(Feature), new PropertyMetadata(""));
}
So after my ospdata is ready I store and at runtime I load the class to populate my UI. but Element name binding is not working.
StringReader stringReader = new StringReader(File.ReadAllText("Model/OSPData.xaml"));
XmlReader xmlReader = XmlReader.Create(stringReader);
var data = (OSPData)XamlReader.Load(xmlReader);
SimpleIoc.Default.GetInstance<TestingViewModel>().Data = data;
and my ui look like this :
<UniformGrid>
<ListBox ItemsSource="{Binding Data.Features}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBox Text="{Binding LocalName}" Width="100" />
<CheckBox Content="IsEnabled" IsChecked="{Binding IsEnabled}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</UniformGrid>
I want the ability to edit OSPData.xaml and push it to application at runtime.
I have a little problem here. I've created custom TreeView using RadTreeView. It all works nice, but I've encountered an obstacle. I've set DependencyProperty for SelectedItem in TreeView. I nest my control in View, bind property to SelectedItem in TwoWay mode, but bound property won't update, it's null all the time, despite DependencyProperty value being set.
Here's tree xaml:
<Grid xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
xmlns:sdk='http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk'
xmlns:telerik='http://schemas.telerik.com/2008/xaml/presentation' x:Name='this' >
<Grid.Resources>
<DataTemplate x:Key='ChildTemplate'>
<TextBlock Text='{Binding Path=ChildPath}' Margin='5,0' />
</DataTemplate>
<telerik:HierarchicalDataTemplate x:Key='NameTemplate' ItemsSource='{Binding ChildrenCollectionPath}' ItemTemplate='{StaticResource ChildTemplate}'>
<TextBlock Text='{Binding Path=ParentPath }' Padding='7'/>
</telerik:HierarchicalDataTemplate>
</Grid.Resources>
<telerik:RadTreeView x:Name='rtvTreeView' Padding='5' BorderThickness='0' IsEditable='False' IsLineEnabled='True' IsExpandOnDblClickEnabled='False' ItemTemplate='{StaticResource NameTemplate}' />
</Grid>
Below is way I nest the control in View:
<windows:TreeViewReuse CollectionSource="{Binding SitesCollectionWithAddress}" ParentPath="Napis" Grid.Column="0" BorderThickness="2" SelectedItemD="{Binding SelectedSide, ElementName=this, UpdateSourceTrigger=Explicit, Mode=TwoWay}" ChildPath="FullAddress" ChildrenCollectionPath="AdresyStrony" BorderBrush="Red" DoubleClickCommand="{Binding TreeViewDoubleClick}">
</windows:TreeViewReuse>
And here's Tree's code behind in parts:
public partial class TreeViewReuse : UserControl
{
static Telerik.Windows.FrameworkPropertyMetadata propertyMetaData = new Telerik.Windows.FrameworkPropertyMetadata(null,
Telerik.Windows.FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, new PropertyChangedCallback(SelectedItemChangedCallback));
public object SelectedItemD
{
get { return GetValue(SelectedItemDProperty); }
set { SetValue(SelectedItemDProperty, value); }
}
public static readonly DependencyProperty SelectedItemDProperty =
DependencyProperty.Register("SelectedItemD", typeof(object), typeof(TreeViewReuse), propertyMetaData);
public TreeViewReuse()
{
InitializeComponent();
Loaded += new RoutedEventHandler(TreeViewReuse_Loaded);
}
void treeView_SelectionChanged(object sender, Telerik.Windows.Controls.SelectionChangedEventArgs e)
{
SelectedItemD = _treeView.SelectedItem;
}
static private void SelectedItemChangedCallback(DependencyObject dp, DependencyPropertyChangedEventArgs e)
{
}
Does anyone have an idea why property bound to SelectedItemD does not update? I don't care about setting tree's selected item from it, I only want to set it to selected item.
Here's property:
public StronaSprawy SelectedSide
{
get
{
return _selectedSide;
}
set
{
_selectedSide = value;
}
}
Your Dependency Property looks fine.. all except for that Telerik.Windows.FrameworkPropertyMetadata instance.
Silverlight does not support setting meta data options, so I cant think how the Telerik implementation will achieve that. It is possible that Telerik have their own DP implementation, or even that this type of property meta data only works with their controls.
Try using the standard System.Windows.PropertyMetaData type instead and see if that works for you.
I have created a user control with collection property:
public static readonly DependencyProperty
MyListProperty = DependencyProperty.Register(
"MyList",
typeof(ObservableCollection<Test>),
typeof(UserControl1),
new FrameworkPropertyMetadata(new ObservableCollection<Test>())
);
public ObservableCollection<Test> MyList
{
get { return (ObservableCollection<Test>)base.GetValue(MyListProperty); }
set { base.SetValue(MyListProperty, value); }
}
public static readonly DependencyProperty
BProperty = DependencyProperty.Register(
"B",
typeof(string),
typeof(UserControl1),
new FrameworkPropertyMetadata(null)
);
public string B
{
get { return (string)base.GetValue(BProperty); }
set { base.SetValue(BProperty, value); }
}
The Test class is:
public class Test : DependencyObject
{
public static readonly DependencyProperty
AProperty = DependencyProperty.Register(
"A",
typeof(string),
typeof(Test),
new FrameworkPropertyMetadata(null)
);
public string A
{
get { return (string)base.GetValue(AProperty); }
set { base.SetValue(AProperty, value); }
}
}
Then, i'm trying to use my control for binding:
<TextBox x:Name="tb1" Text="def"/>
<my:UserControl1 x:Name="uc1" B="{Binding ElementName=tb1, Path=Text}">
<my:UserControl1.MyList>
<my:Test A="{Binding ElementName=tb1, Path=Text}"></my:Test>
<my:Test A="100"></my:Test>
</my:UserControl1.MyList>
</my:UserControl1>
The first binding (with B property of User Control) works correctly. The problem is with second binding (with A property of Test which is MyList element). When debugging i have two items in MyList but the A property of the first one is null. Please tell me what I am missing here?
The problem here is, that the Binding to ElementName=tb1 can not be resolved, even it will never be evaluated. A Binding to an ElementName is resolved for DependencyObjects which are in the visual or logical Tree of a WPF Application. Adding items to your ObservableCollection (MyList) only means adding the items to the Collection, but not into the Visual Tree.
Edit:
Here is the approach discussed in the comments:
In your Window/Page:
<Window.Resources>
<!-- Declare the ViewModel as Resource -->
<my:ViewModel x:Key="viewModel">
<my:ViewModel.MyList>
<my:Test A="Hello sweet" />
<my:Test A="ViewModel" />
</my:ViewModel.MyList>
</my:ViewModel>
</Window.Resources>
<!-- Assign Ressource as DataContext -->
<StackPanel DataContext="{StaticResource viewModel}">
<TextBox x:Name="tb1" Text="def"/>
<!-- Reference your list within the ViewModel -->
<ListBox ItemsSource="{Binding Path=MyList}">
<ListBox.ItemTemplate>
<DataTemplate>
<!-- Bind your property -->
<TextBlock Text="{Binding Path=A}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
And the implementation of ViewModel:
public class ViewModel
{
public ViewModel()
{
this.MyList = new ObservableCollection<Test>();
}
public ObservableCollection<Test> MyList { get; set; }
}
Of course, class Test no longer needs to implement a DependencyObject. Simple get/set Properties are okay.
I have created a user control like numeric updown as follows
<StackPanel Orientation="Horizontal" VerticalAlignment="Top" >
<TextBox x:Name="InputTextBox" Grid.Row="0" Grid.Column="0" Grid.RowSpan="1"
Style="{StaticResource NumericUpDownTextBoxStyle}"
KeyDown="InputTextBox_KeyDown"
KeyUp="InputTextBox_KeyUp"
GotFocus="InputTextBox_GotFocus"
LostFocus="InputTextBox_LostFocus"
MouseWheel="InputTextBox_MouseWheel"
MouseEnter="InputTextBox_MouseEnter"
LayoutUpdated="InputTextBox_LayoutUpdated"
Text="{Binding Path=ControlValue, Mode=TwoWay,ValidatesOnDataErrors=True,ValidatesOnExceptions=True,NotifyOnValidationError=True}"/>
</StackPanel>
I have bind a ViewModel to this control where I Set ControlValue property to TextBox property of the user control template textbox.
Everthing works fine at a control level. I have exposed from usercontrol.
public static readonly DependencyProperty MaximumValueProperty;
public static readonly DependencyProperty MinimumValueProperty;
public static readonly DependencyProperty StepValueProperty;
public static readonly DependencyProperty TextValueProperty;
My Properties are
public double Maximum
{
get
{
return (double)GetValue(MaximumValueProperty);
}
set
{
SetValue(MaximumValueProperty, value);
this.ViewModel.Maximum = this.Maximum;
}
}
public double Minimum
{
get
{
return (double)GetValue(MinimumValueProperty);
}
set
{
SetValue(MinimumValueProperty, value);
this.ViewModel.Minimum = this.Minimum;
}
}
public double Step
{
get
{
return (double)GetValue(StepValueProperty);
}
set
{
SetValue(StepValueProperty, value);
this.ViewModel.Step = this.Step;
}
}
public double TextValue
{
get
{
return (double)GetValue(TextValueProperty);
}
set
{
SetValue(TextValueProperty, value);
this.ViewModel.ControlValue = Convert.ToString(value);
}
}
Initialization of the property.
static NumericUpDown()
{
MaximumValueProperty = DependencyProperty.Register("Maximum", typeof(double), typeof(NumericUpDown), new PropertyMetadata(null));
MinimumValueProperty = DependencyProperty.Register("Minimum", typeof(double), typeof(NumericUpDown), new PropertyMetadata(null));
StepValueProperty = DependencyProperty.Register("Step", typeof(double), typeof(NumericUpDown), new PropertyMetadata(null));
TextValueProperty = DependencyProperty.Register("TextValue", typeof(double), typeof(NumericUpDown), new PropertyMetadata(null));
}
My Usercontrol implementation in the MainPage.xaml page as follows
<local:NumericUpDown Maximum="28" Minimum="-28" Step="0.25" TextValue="{Binding ElementName=FranePrice, Path=DataContext.FranePrice}"></local:NumericUpDown>
Where I have another ViewModel which i bind to the XAML page and there is a Property in the ViewModel which i bind to the TextValue property of the Usercontrol.
FramePrice is property in the View model that i bind to the TextValue property of the user control
and Main page XAML is
<UserControl x:Class="DatePicker.MainPage"
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:DatePicker"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">
<Grid x:Name="LayoutRoot" Background="White">
<StackPanel Orientation="Vertical">
<local:NumericUpDown Maximum="28" Minimum="-28" Step="0.25" TextValue="{Binding ElementName=FranePrice, Path=DataContext.FranePrice}"></local:NumericUpDown>
<Button Content="Show Date" Height="23" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click"/>
</StackPanel>
</Grid>
This View model of the page where i used user control. On click event i showing TextValue to user.
public class MainPageViewModel : EntityViewModel
{
public MainPageViewModel()
{
}
private double framePrice;
public Double FramePrice
{
get
{
return framePrice;
}
set
{
framePrice = value;
PropertyChangedHandler("FramePrice");
}
}
}
When I change the TextValue in the User control it doesnot change in the FramePrice property of the page viewmodel.
Is anything wrong in the code.???
As per Luke Woodward's post I have updated code as follows
public static readonly DependencyProperty MaximumValueProperty;
public static readonly DependencyProperty MinimumValueProperty;
public static readonly DependencyProperty StepValueProperty;
public static readonly DependencyProperty TextValueProperty;
public static double Max;
public static double Min;
public static double Stp;
public static double Val;
public double Maximum
{
get
{
return (double)GetValue(MaximumValueProperty);
}
set
{
SetValue(MaximumValueProperty, value);
}
}
public double Minimum
{
get
{
return (double)GetValue(MinimumValueProperty);
}
set
{
SetValue(MinimumValueProperty, value);
}
}
public double Step
{
get
{
return (double)GetValue(StepValueProperty);
}
set
{
SetValue(StepValueProperty, value);
}
}
public double TextValue
{
get
{
return (double)GetValue(TextValueProperty);
}
set
{
SetValue(TextValueProperty, value);
}
}
static NumericUpDown()
{
MaximumValueProperty = DependencyProperty.Register("Maximum", typeof(double), typeof(NumericUpDown), new PropertyMetadata(new PropertyChangedCallback(onMaximumValueChanged)));
MinimumValueProperty = DependencyProperty.Register("Minimum", typeof(double), typeof(NumericUpDown), new PropertyMetadata(new PropertyChangedCallback(onMinimumValueChanged)));
StepValueProperty = DependencyProperty.Register("Step", typeof(double), typeof(NumericUpDown), new PropertyMetadata(new PropertyChangedCallback(onStepValueChanged)));
TextValueProperty = DependencyProperty.Register("TextValue", typeof(double), typeof(NumericUpDown), new PropertyMetadata(new PropertyChangedCallback(onTextValueChanged)));
}
private static void onStepValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
Stp = (double)e.NewValue;
}
private static void onMinimumValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
Min = (double)e.NewValue;
}
private static void onMaximumValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
Max = (double)e.NewValue;
}
private static void onTextValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
Val = (double)e.NewValue;
}
Then i accessed Max, Min , Stp and Val property in user control's view model to perform my logic.
and XAML code is follows
<local:NumericUpDown x:Name="ctlUpDown" Maximum="28" Minimum="-28" Step="0.25" TextValue="{Binding Path=FramePrice}"></local:NumericUpDown>
and XAML of user control
<StackPanel Margin="5" Orientation="Horizontal" VerticalAlignment="Center">
<TextBox x:Name="InputTextBox" Grid.Row="0" Grid.Column="0" Grid.RowSpan="1"
Height="23" VerticalAlignment="Top"
Width="50" TextAlignment="Center"
KeyDown="InputTextBox_KeyDown"
KeyUp="InputTextBox_KeyUp"
GotFocus="InputTextBox_GotFocus"
LostFocus="InputTextBox_LostFocus"
MouseWheel="InputTextBox_MouseWheel"
MouseEnter="InputTextBox_MouseEnter"
Text="{Binding Path=TextValue, ElementName=ctlUpDown, Mode=TwoWay,ValidatesOnDataErrors=True,ValidatesOnExceptions=True,NotifyOnValidationError=True}"
/>
</StackPanel>
The first thing I noticed wrong about your code was the properties Maximum, Minimum, Step and TextValue. Here's the TextValue property:
public double TextValue
{
get
{
return (double)GetValue(TextValueProperty);
}
set
{
SetValue(TextValueProperty, value);
this.ViewModel.ControlValue = Convert.ToString(value);
}
}
Properties that are backed by a dependency property, such as the four I mentioned above, should ALWAYS look like the following:
public double TextValue
{
get { return (double)GetValue(TextValueProperty); }
set { SetValue(TextValueProperty, value); }
}
In other words, the getter should contain nothing more than a call to GetValue, and the setter should contain nothing more than a call to SetValue.
The reason for this is that when Silverlight changes the value of the TextValue dependency property, it won't do it by using the property above. The values of dependency properties are stored within the Silverlight dependency system, and when Silverlight wants to change the value of one of them, it goes directly to this dependency system. It doesn't call your code at all. Properties like that above are provided only for your convenience, giving you an easy way to access and change the value stored in the dependency property. They will never be called by anything other than your own code.
Generally, if you want a method to be called whenever a dependency property value changes, you need to pass a PropertyChangedCallback in the PropertyMetadata when registering the dependency property. However, I suspect that in your case you won't need to do that.
It seems to me that you have three properties:
the FramePrice property in your view-model class,
the TextValue dependency property of your NumericUpDown user control,
the Text dependency property of the TextBox within your NumericUpDown user control's XAML.
My impression is that you want the FramePrice property in your view-model to always have the same value as the Text property of the TextBox. To do that, you need to bind the FramePrice property to the NumericUpDown's TextValue property, and then bind that to the Text property of the TextBox.
To bind the first two of these properties together, there are a couple of things to change. Firstly, the TextValue property in your <local:NumericUpDown> element should look like
TextValue="{Binding Path=FramePrice}"
The binding {Binding ElementName=FramePrice, Path=DataContext.FramePrice} won't work, because there's no element in your XAML with the attribute x:Name="FramePrice". The value of an ElementName property in a {Binding ...} must match the x:Name of an object in the XAML.
You also need to set up the DataContext for your main page. If your main page view-model object has a zero-argument constructor, one way of doing this is to follow this answer.
To bind the second two properties together, I would:
add an x:Name attribute to the <UserControl> element of your NumericUpDown control (x:Name="ctlUpDown", say),
replace the Text property of the TextBox within your NumericUpDown control with the following:
Text="{Binding Path=TextValue, ElementName=ctlUpDown, Mode=TwoWay, ValidatesOnDataErrors=True, ValidatesOnExceptions=True, NotifyOnValidationError=True}"/>
Once you've done that, you can then remove all of the lines this.ViewModel.SomeProperty = ... from your code-behind class. They're not necessary, and as I've already explained they won't be run when you wanted them to.
Finally, is there a reason you're not using the Silverlight Toolkit's NumericUpDown control?
EDIT 2: Against my better judgement I took a look at one of the two Silverlight projects you uploaded (I ignored the one with _2 in it). It bears very little resemblance to your question.
I can only assume you want the two textboxes (one of which is in a user control) to always have the same value. I was able to do this after making the following changes:
MainPageViewModel.cs: add ClearErrorFromProperty("DPropertyBind"); to the property setter. (Otherwise the validation error never gets cleared.)
MyUserControlWVM.xaml: removed reference to LostFocus event handler, added binding on Text property and added add x:Name attribute to the <UserControl> element. In other words, it now looks like the following:
<UserControl x:Class="DependencyPropertyBinding.MyUserControlWVM"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Name="ctlWVM"
d:DesignHeight="300" d:DesignWidth="205">
<StackPanel Orientation="Horizontal" Width="204" Height="32">
<TextBox x:Name="textbox" Height="30" Width="200" Text="{Binding Path=DProperty, ElementName=ctlWVM, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnDataErrors=True, ValidatesOnExceptions=True}" />
</StackPanel>
</UserControl>
MyUserControlWVM.xaml.cs: renamed dependency property DependencyPropertyValue to DPropertyProperty (the naming convention is that the static readonly field has the name of the property (in this case DProperty) with Property appended). I also removed the TextBox_LostFocus event handler.
If the code above is accurate you have spelt FramePrice as FranePrice in the binding
The output window should have shown this as a binding error when the page loaded.
it is currently
Binding ElementName=FranePrice, Path=DataContext.FranePrice
should be:
Binding ElementName=FramePrice, Path=DataContext.FramePrice
"With great binding capabilities comes great responsibility" :)
I am writing a WPF program in C# in which I have a ListView for which the columns will be populated at runtime. I would like to use a custom DataTemplate for the GridViewColumn objects in the ListView.
In the examples I have seen where the number of columns is fixed in advance, a custom DataTemplate is often created using something like the XAML below.
<DataTemplate x:Key="someKey">
<TextBlock Text="{Binding Path=FirstName}" />
</DataTemplate>
This DataTemplate could also later be assigned to GridViewColumn.CellTemplate in the code-behind by calling FindResource("someKey"). However, this alone is of no use to me, because in this example the Path element is fixed to FirstName. Really I need something where I can set the Path in code.
It is my impression that something along these lines may be possible if XamlReader is used, but I'm not sure how in practice I would do this. Any solutions are greatly appreciated.
It is easy to build what you need using two DataTemplates working in concert: The outer DataTemplate simply sets the DataContext for the inner DataTemplate, as follows:
<DataTemplate x:Key="DisplayTemplate">
<Border ...>
<TextBlock Text="{Binding}" ... />
</Border>
</DataTemplate>
<DataTemplate x:Key="CellTemplate">
<ContentPresenter Content="{Binding FirstName}"
ContentTemplate="{StaticResource DisplayTemplate}" />
</DataTemplate>
The only tricky thing is making it convenient to set this on a GridViewColumn. I would accomplish this with attached properties, allowing you to write:
<GridViewColumn
my:GVCHelper.DisplayPath="FirstName"
my:GVCHelper.Template="{StaticResource DisplayTemplate}" />
Or equivalently in code:
var col = new GridViewColumn();
GVCHelper.SetDisplayPath(col, "FirstName");
GVCHelper.SetTemplate(col, (DataTemplate)FindResource("DisplayTemplate"));
Either of these would cause the DataTemplate named "DisplayTemplate" to be used to display the FirstName in the column.
The helper class would be implemented as:
public class GVCHelper : DependencyObject
{
public static string GetDisplayPath(DependencyObject obj) { return (string)obj.GetValue(DisplayPathProperty); }
public static void SetDisplayPath(DependencyObject obj, string value) { obj.SetValue(DisplayPathProperty, value); }
public static readonly DependencyProperty DisplayPathProperty = DependencyProperty.RegisterAttached("DisplayPath", typeof(string), typeof(GVCHelper), new PropertyMetadata
{
PropertyChangedCallback = (obj, e) => Update(obj)
});
public static DataTemplate GetTemplate(DependencyObject obj) { return (DataTemplate)obj.GetValue(TemplateProperty); }
public static void SetTemplate(DependencyObject obj, DataTemplate value) { obj.SetValue(TemplateProperty, value); }
public static readonly DependencyProperty TemplateProperty = DependencyProperty.RegisterAttached("Template", typeof(DataTemplate), typeof(GVCHelper), new PropertyMetadata
{
PropertyChangedCallback = (obj, e) => Update(obj)
});
private static void Update(DependencyObject obj)
{
var path = GetDisplayPath(obj);
var template = GetTemplate(obj);
if(path!=null && template!=null)
{
var factory = new FrameworkElementFactory(typeof(ContentPresenter));
factory.SetBinding(ContentPresenter.ContentProperty, new Binding(path));
factory.SetValue(ContentPresenter.ContentTemplateProperty, template);
obj.SetValue(GridViewColumn.CellTemplateProperty,
new DataTemplate { VisualTree = factory };
}
}
}
How it works: Whenever the properties are both set, a new DataTemplate is constructed and the GridViewColumn.CellTemplate property is updated.
Maybe GridViewColumn.CellTemplateSelector would help you? Or you could create a user control, bind it to something big enough (that's the same for each column). Then let this control figure out what exactly it should display based on what it has in DataContext...