WPF binding subcontrols to a parent control
I am trying to perform databinding, given the following case:
I have a class called "Node" that has two properties: "speed" and "pauseTime". I then have an array of Nodes.
In my XAML, I 开发者_开发技巧have a numeric control (labeled Node) that allows the user to switch between Nodes. There are also two subcontrols which I want to have show speed and pauseTime for the selected Node.
My question is how do I set the databinding for speed, for example, so that it shows the speed for the selected Node in the Nodes array based on the value in the Node numeric control?
I tried googling this, but am not sure what search terms to use.
I'm not sure what you mean by numeric control, but I knocked up an example of a master details control scenario.
In the XAML you have a Grid with a ListView (the master), and a TextBlock (the details):
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<ListView ItemsSource="{Binding}" x:Name="masterListView">
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<TextBlock Grid.Row="1" Text="{Binding ElementName=masterListView, Path=SelectedItem.Speed}" />
</Grid>
The code behind looks like this:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new Node[]
{
new Node() { Speed = 1, PauseTime = "1 Min", Name = "Item 1" },
new Node() { Speed = 2, PauseTime = "2 Mins" , Name = "Item 2" }
};
}
}
public class Node
{
public int Speed { get; set; }
public string PauseTime { get; set; }
public string Name { get; set; }
}
The child TextBlock binds to the Speed property of the Selected node. If you add IsSynchronizedWithCurrentItem="True" to the ListView, the first item will automatically be selected when the window is loaded. If you Google master details/WPF and IsSynchronizedWithCurrentItem="True" you will find more details.
It would probably also be useful to Google how to do this using MVVM- a reasonable approach is mentioned in this Stackoverflow Answer.
精彩评论