Reputation: 39298
I have a few controls, the values of which are used in the view but aren't of any concern in the view model. I'd like to bind the controls to properties in the view without having to replicate them down to view model.
According to a similar question's reply, it's possible and I'm using the following code to achieve that. However, when I don't see the expected results, so I'm guessing that I'm unintentionally binding to a flagpole, not the intended property.
XAML
<DatePicker x:Name="Uno"
SelectedDate="{Binding StartDate, Source={x:Static Application.Current}}"
SelectedDateChanged="DatePicker_OnSelectedDateChanged" />
<DatePicker x:Name="Due"
SelectedDate="{Binding StartDate, Source={x:Static Application.Current}}"
SelectedDateChanged="DatePicker_OnSelectedDateChanged" />
C#
public partial class ViewWindow : Window
{
public static DateTime StartDate { get; set; }
...
}
What am I missing in my code? Or have I misunderstood the reply and going about it all the wrong way?
Upvotes: 2
Views: 644
Reputation: 37800
This:
x:Static Application.Current
tries to set Application.Current
as a binding source for the particular binding expression. But, obviously, you don't want to access something like Application.Current.StartDate
(I suppose, that your App
class doesn't have such property defined).
Actually, I've missed static
keyword from your property definition.
If you're on the .NET 4.5 or higher, you can write binding path this way for static properties:
<DatePicker x:Name="Uno"
SelectedDate="{Binding Path=(local:ViewWindow.StartDate)}"
SelectedDateChanged="DatePicker_OnSelectedDateChanged" />
local
here is a namespace, where ViewWindow
is defined.
Otherwise, use RelativeSource
markup extension (this also fits the case, when the property is instance):
<DatePicker x:Name="Uno"
SelectedDate="{Binding StartDate,
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType={x:Type Window}}}"
SelectedDateChanged="DatePicker_OnSelectedDateChanged" />
Upvotes: 4