[英]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 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# 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. 尝试将
Application.Current
设置为特定绑定表达式的绑定源。 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). 但是,显然,您不想访问诸如
Application.Current.StartDate
类的东西(我想,您的App
类未定义此类属性)。
Actually, I've missed static
keyword from your property definition. 实际上,我从您的属性定义中错过了
static
关键字。
If you're on the .NET 4.5 or higher, you can write binding path this way for static properties: 如果您使用的是.NET 4.5或更高版本,则可以通过以下方式为静态属性编写绑定路径:
<DatePicker x:Name="Uno"
SelectedDate="{Binding Path=(local:ViewWindow.StartDate)}"
SelectedDateChanged="DatePicker_OnSelectedDateChanged" />
local
here is a namespace, where ViewWindow
is defined. local
这里是一个命名空间,在其中定义了ViewWindow
。
Otherwise, use RelativeSource
markup extension (this also fits the case, when the property is instance): 否则,请使用
RelativeSource
标记扩展(当该属性是instance时,这也适用):
<DatePicker x:Name="Uno"
SelectedDate="{Binding StartDate,
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType={x:Type Window}}}"
SelectedDateChanged="DatePicker_OnSelectedDateChanged" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.