开发者

Bind boolean value

I have been working on a C# 4.0 WPF project and need to figure out how to databind a Boolean value. I have a reference to my Application.Current object in a window. My "App" object contains a boolean field called "Downloaded" that is true if the user has downloaded information from a web service. I need to databind a textbox's IsEnabled field to this Downloaded value. Any tips? Here is what I have come up with so far. (Any useful links to better learn WPF XAML are greatly appreciated!)

C# code:

class MainWindow : Window
{
    private App MyApp = App.Current as App; 
}

XAML:

<TextBox ... IsEnabled="{Binding Source=MyApp, Path=Downloaded}" />开发者_运维知识库


WPF can't resolve that Source. If you're specifying a Source in XAML, it will typically be a resource elsewhere in the XAML (e.g. an ObjectDataProvider). MyApp is actually a path from your Window object, not a source in itself.

What you probably want is a multipart path:

{Binding Path=MyApp.Downloaded}

However, you'll still have a few problems with this:

  1. MyApp is a private field. WPF allows binding only to properties (and they should normally be public). So change MyApp to be a public property.
  2. The binding shown is relative to the local DataContext, which will not by default be the Window. So you either need to set the DataContext to the Window (generally poor style), place the MyApp property on a view model class and set the Window.DataContext to be that view model (generally the recommended style) or use a RelativeSource or ElementName on the binding to make it resolve the path against the Window object instead of the DataContext.

Note also you must implement INotifyPropertyChanged on your App class, and raise PropertyChanged for the Downloaded property.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜