Recently collaborated with friends an application, the development of the time encountered two problems, the first is a ListBox control multiple selection problem, the second is the Photochoosertask selector and image control of the problem. Coincidentally, some readers in my blog recently mentioned that he also encountered a second problem, so I would like to share in this article how to use additional attributes and Expression blend behavior to solve both problems.
How do I bind the SelectedItems property of a ListBox control?
When we set the value of the SelectionMode property to multiple, the ListBox control can support multiple selections, as shown in Figure 1, at which point we can get the selected item through the SelectedItems property of the ListBox control. Next, I would naturally think of binding the ItemsSource and SelectedItems two properties of the ListBox control to the corresponding properties of the view model, but what if the SelectedItems property is not a dependent property and cannot be data bound?
Figure 1
Since the SelectedItems attribute does not support data binding, we create a support data binding ourselves. In Silverlight, we can extend dependent objects through additional attributes, for example, we can set grid.row attached properties on a ListBox control, as shown in code 1.
Code 1
Grid.Row attached properties are not properties of the ListBox control, but are used to append additional data. Setting the Grid.Row attached property on the ListBox control does not itself have any effect, but when we put the ListBox control in a grid, This grid will arrange the position of the ListBox control based on the value of the Grid.Row attached property, which is a common use for additional properties.
Back to our question, I want to create a selecteditems attached property as a bridge between the attributes of the SelectedItems attribute and the view model, as shown in code 2. When we bind the SelectedItems attached property to the corresponding property of the view model, the former adds the latter's data to the SelectedItems property that comes with it. When the user changes the selected item in the user interface, the SelectedItems attached property updates the data back to the corresponding property of the view model.
Code 2