简体   繁体   中英

How to bind to a property in view but not in viewmodel?

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?

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" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM