textbox is being filled but datepicker is not via mvvm binding - wpf

I have a textbox with a date in it and I want to convert it to a datepicker for twoway binding. But unfortunately the datepicker doesn't show the date.
<TextBox Grid.Row="1"
Grid.Column="4"
IsReadOnly="False"
Text="{Binding Path=BirthDate,
Mode=OneWay,
StringFormat='dd/MM/yyyy'}" />
The following code does not work, the selecteddate shows empty... (while there is a value in it)
<DatePicker Grid.Row="1"
Grid.Column="4" FirstDayOfWeek="Monday" SelectedDate="{Binding BirthDate, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" ></DatePicker>
In another location in the application I also have a datepicker that Does work:
<DatePicker x:Name="DatePicker"
Grid.Row="3"
Grid.Column="1"
FirstDayOfWeek="Monday"
SelectedDate="{Binding Parameter.PAR_Date,
Mode=TwoWay}" />
I can't see what I'm doing wrong, it seems very simple.
I can just type a date in the datepicker and this works... so very strange... any ideas would be welcome...
EDIT:
Got a step closer by using snoop and looking in to the binding on the datepicker and it seems to have an error, I seem to have a different expected type:
System.Windows.Data Error: 1 : Cannot create default converter to perform 'two-way' conversions between types 'EVD.Framework.NullableDateTime' and 'System.Nullable`1[System.DateTime]'. Consider using Converter property of Binding. BindingExpression:Path=Birthdate; DataItem='SomeModel' (HashCode=31671132); target element is 'DatePicker' (Name=''); target property is 'SelectedDate' (type 'Nullable`1')
System.Windows.Data Error: 5 : Value produced by BindingExpression is not valid for target property.; Value='04/10/1929' BindingExpression:Path=Birthdate; DataItem='SomeModel' (HashCode=31671132); target element is 'DatePicker' (Name=''); target property is 'SelectedDate' (type 'Nullable`1')
EDIT 2:
That was it, in the code the datetime was a NullableDateTime. Thanks to everyone pitching in ideas, especially Viv. Votes up for everyone with a decent suggestion :-)

This article does a good job explaining StringFormat:
http://elegantcode.com/2009/04/07/wpf-stringformat-in-xaml-with-the-stringformat-attribute/
You need to remember to use {0} when formatting.

Related

Binding Error Reported with Converter in WPF Textbox

a textbox is either hidden or not depending on whether its text is null or not.
The actual hiding works ok but i keep getting a Data.Error as follows.
System.Windows.Data Error: 40 : BindingExpression path error: 'new_file_path' property not found on 'object' ''main_window_vm' (HashCode=44962972)'. BindingExpression:Path=new_file_path; DataItem='main_window_vm' (HashCode=44962972); target element is 'Run' (HashCode=28141317); target property is 'Text' (type 'String')
xaml is
<Padding="10" Visibility="{Binding Path=Text, RelativeSource={RelativeSource Self},
Converter={StaticResource null_to_viz}}">
<Run Text="Updated file path : " />
<Run Text="{Binding new_file_path}" />
any ideas to fix this error?
The issue is complaining about not finding new_file_path yet the example is binding to the property Text.
Most likely this converter is not failing and it is a different control. Investigate by either finding the right control which is not binding properly or verifying that textbox is actually binding to the proper VM.
seems like this error occurs when one foolishly set a property to private, not public. Which is why it was not able to be found.

wpf debug error output System.WIndows.Data Error 25

I have a custom styled Combobox which works fine. It is placed inside a usercontrol and bound to a data structure. I use DisplayMemberPath to show only one element in the Combobox TextBox. The ComboBox Style is taken from MSDN and used many times. So it's not displayed here.
<UserControl x:Class="wpf.projext1.MyComboBox"
x:Name="MyControl"
...
<ComboBox Style="{StaticResource ComboBoxStyle}"
Text="{Binding ElementName=MyControl, Path=Text}"
IsEditable="True"
IsTextSearchEnabled="False"
StaysOpenOnEdit="True"
ItemsSource="{Binding ElementName=MyControl, Path=MyItemsSource}"
DisplayMemberPath="Name"
</ComboBox
I get the following annoying error message populating the output window:
System.Windows.Data Error: 25 : Both 'ContentTemplate' and 'ContentTemplateSelector' are set; 'ContentTemplateSelector' will be ignored. ComboBoxItem:'ComboBoxItem' (Name='')
if i leave out the
DisplayMemberPath="Name"
... no debug output about error 25 is shown. But I definitely need DiplayMemberPath="Name"!
Do You have an idea to fix this ?
You canĀ“t set both DisplayMemberPath and ItemTemplate at the same time.
DisplayMemberPath is used to tell the ItemsControl which property to display when showing your objects. It makes no sense to set this field if you're already passing a custom ItemTemplate, since you can choose how to show the object within that ItemTemplate.
Since the default Combobox style from MSDN also sets an ItemTemplate, this is likely the cause of the error.
resolved: use the TextSearch attached property, no matter if TextSearch is enabled!
TextSearch.TextPath="Name"
Should note TextSearch.TextPath="Name" instead of DisplayMemberPath="Name".

Custom DateTime stringformat in WPF

I can't get my custom DateTime string format to work in my binding. I want the format to be "mmmm, yyyy" (e.g. "June, 2012").
The following does not work. I get a short date format (m/d/yyyy).
<TextBlock Text="{Binding ElementName=ThisWindow,
Path=Date,
StringFormat={}{0:MMMM\, yyyy}"/>
I've considered using a converter, but I prefer a pure XAML approach.
Edit:
For clarity, I have a Window with a dependency property Date of type DateTime. In my XAML, I've named the window 'Thiswindow'.
Edit 2:
I looked back at my actual code, and I had a Label, not a TextBlock. I changed it to TextBlock and it works fine.
<Label Content="{Binding ElementName=ThisWindow,
Path=Date,
StringFormat={}{0:MMMM\, yyyy}"/>
Anyone know why it doesn't work with Label?
Thanks.
ContentControls have a ContentStringFormat property which overrides the original formatting.
(When i saw your question i expected this to be the problem actually but was surprised to find a TextBlock at first)
Your month needs to be in uppercase:
{Binding Source={x:Static sys:DateTime.Now}, StringFormat={}{0:MMMM\, yyyy}}
EDIT:
The Label problem is probably because Label has Content, not Text.
Change the Text="{Binding ...}" to Content="{Binding ...}"

Why does data binding break in OneWay mode?

Here's a little XAML fragment. You will see
<StackPanel>
<TextBox x:Name="txtValue">250</TextBox>
<Slider x:Name="slide"
Value="{Binding ElementName=txtValue, Path=Text,
Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
Minimum="0" Maximum="500"></Slider>
</StackPanel>
when you change the textbox value, the slider updates
If you change the slider value explicitly, the previous behavior breaks a.k.a. stops working.
If I remove the Mode=OneWay set directive, (defaults to two-way) everything works perfectly.
Why is this happening?
Use mode=TwoWay and set the UpdateSourceTrigger=Explicit.
Your data binding is not broken but deactivated (http://en.wikipedia.org/wiki/Euphemism):
System.Windows.Data Warning: 75 : BindingExpression (hash=52697953): Deactivate
System.Windows.Data Warning: 99 : BindingExpression (hash=52697953): Replace item at level 0 with {NullDataItem}
System.Windows.Data Warning: 59 : BindingExpression (hash=52697953): Detach
Setting the trace level to high will produce this message in the VS output window in case you move the slider:
<Slider xmlns:trace="clr-namespace:System.Diagnostics;assembly=WindowsBase"
Value="{Binding trace:PresentationTraceSources.TraceLevel=High,
ElementName=txtValue, Path=Text, Mode=OneWay,
UpdateSourceTrigger=PropertyChanged}"
Minimum="0" Maximum="500"></Slider>
If you create a control which inherits from Slider, then override the Value property and use DependencyObject.SetCurrentValue when changing the value rather than DependencyOpbject.SetValue, then your databindings will be preserved when changing the values programmatically.
Sorry this isn't particularly exhaustive, will update this answer to include a basic implementation of this at a later date.
Alternatively, a UserControl which contains both the textbox and the slider would make for a very reusable implementation, in which you could bind them both to the same custom dependencyproperty, make the binding oneway, hijack the valuechanged event of the slider, set e.Handled = true, and call the SetCurrentValue function from that.

WPF: Collection dependency property "is read-only and cannot be set from markup"

I am creating a user control to display a three-month calendar. The control is based on the WPF Calendar control (WPF Toolkit 2009-06), and I want to pass several of the Calendar's properties through to corresponding properties of my user control. The user control properties are set up as Dependency Properties, and their underlying types match the types of the Calendar properties. Here is my markup:
<StackPanel>
<toolkit:Calendar Name="MasterCalendar"
SelectionMode="{Binding Path=SelectionMode, Mode=OneWay}"
SelectedDate="{Binding Path=SelectedDate, Mode=OneWayToSource}"
SelectedDates="{Binding Path=SelectedDates, Mode=OneWayToSource}"/>
<toolkit:Calendar Name="SlaveCalendar1"
DisplayDate="{Binding DisplayDate, Converter={StaticResource IncrementalMonthConverter}, ElementName=MasterCalendar, Mode=OneWay}"
SelectionMode="{Binding Path=SelectionMode, Mode=OneWay}"
SelectedDate="{Binding Path=SelectedDate, Mode=OneWayToSource}"
SelectedDates="{Binding Path=SelectedDates, Mode=OneWayToSource}"/>
<toolkit:Calendar Name="SlaveCalendar2"
DisplayDate="{Binding DisplayDate, Converter={StaticResource IncrementalMonthConverter}, ElementName=SlaveCalendar1, Mode=OneWay}"
SelectionMode="{Binding Path=SelectionMode, Mode=OneWay}"
SelectedDate="{Binding Path=SelectedDate, Mode=OneWayToSource}"
SelectedDates="{Binding Path=SelectedDates, Mode=OneWayToSource}"/>
</StackPanel>
All of the properties bind without problem, except for the SelectedDates property. I get the following error on its binding:
'SelectedDates' property is read-only and cannot be set from markup.
I suspect that it is because the SelectedDates property is a collection, but I am not sure how to fix the problem. Can anyone enlighten me on the cause of the problem and suggest a fix? Thanks for your help.
If I understand you well, you have Dependency properties in your code behind that match in name and type the properties of the Calendar Controls in your user control. You are trying to assign the SelectedDates Collection of the various Calendar Controls to the Dependency property of the same name in your code behind.
You can simply do this by a line of code:
this.SelectedDates=SlaveCalendar1.SelectedDates
In an appropriate EventHandler that fires when a selected date is added.
Even though you set the binding to OneWayToSource the SelectedDates= piece of code is an assignment. As the SelectedDates Property has no setter, it is not possible to write this piece of code.
Here you can find a link to the Calendar Control's documentation

Resources