开发者

Changing WPF databindings based on value of another property

开发者 https://www.devze.com 2023-02-19 02:26 出处:网络
I\'m reasonably new to WPF, have developed a couple of apps with code-beinding files and have read up on MVVM (via Schifflett\'s \'in the box\' introduction) prior to starting my current application.

I'm reasonably new to WPF, have developed a couple of apps with code-beinding files and have read up on MVVM (via Schifflett's 'in the box' introduction) prior to starting my current application.

The items I'm work开发者_如何学Cing with have a bunch of generic string properties, plus a Dictionary property called Hours which maps dates to hours worked.

My user interface has a DataGrid view of these items (bound to a collection in the ViewModel), and a combobox which allows the user to select a date (which binds the selected value to SelectedDate in the ViewModel). The DataGrid's Hours column needs to show the number of hours worked in the week (i.e., have the same effect as calling item.Hours[SelectedDate] or similar).

What is the best way to do this? Is it possible to put a variable within the binding expression like {Binding Hours[SelectedDate]}?


The two solutions that immediately come to mind are these:

1) Create an Hours property that is based on your SelectedDate:

public int Hours {get { return calculateHours(SelectedDate); } }

"calculateHours" could either be a method or you could put the calculation in the Setter itself. Make sure that whenever SelectedDate is Set that you raise PropertyChanged for "Hours" as well.

I would use this approach if this Hours calculation is only used in this View from this ViewModel.

2) Create a Value Converter that accepts a date and returns the calculated value. Then bind the Hours to the SelectedDate property:

<TextBlock Text="{Binding SelectedDate, Converter={StaticResource DateToHoursConverter}}"

I would use this approach if the calculation is required in multiple Views or in multiple ViewModels. Value Converters are great for this kind of reuse.


if your property you bind to has an indexer, you can bind to it. you just have to raise INotifyPropertyChanged for this indexer at the right time.

edit: a variable within the binding expression will not work, but you can bind to Hours and use a converter and the SelectedDate as convertparameter to get the value you want. you should have to raise INotifyPropertyChanged for "Hours" when "SeletedDate" changed.

0

精彩评论

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