我的窗口中有两个列表框。第一个列表框" all_styles"显示集合中的样式,第二个列表框" Style_subjects"在第一个列表框中显示所选样式集合中的主题。到目前为止一切都很好!
我想介绍一个按钮,将新主题添加到当前所选样式。有没有办法将按钮绑定到列表框的选定样式,并将新主题添加到绑定选择?这是我目前的代码:
xaml:
<Window x:Class="QuickSlide_2._0.Window1"
x:Name="load_style"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Load_style" Height="300" Width="300" MinHeight="720" MinWidth="1280" WindowStyle="None" AllowsTransparency="True" Background="#B0000000" AllowDrop="True" WindowStartupLocation="CenterScreen" ShowInTaskbar="False">
<Grid>
<Button Content="Close" Height="23" HorizontalAlignment="Left" Margin="1081,65,0,0" Name="close" VerticalAlignment="Top" Width="120" Click="close_Click" />
<Button Content="New style" Height="23" HorizontalAlignment="Left" Margin="326,65,0,0" Name="New_style" VerticalAlignment="Top" Width="120" Click="New_style_Click"/>
<Button Content="New subject" Height="23" HorizontalAlignment="Left" Margin="704,65,0,0" Name="New_subject" VerticalAlignment="Top" Width="120" Click="New_subject_Click" />
<ListBox Height="146" HorizontalAlignment="Left" Margin="74,111,0,0" x:Name="all_styles" VerticalAlignment="Top" Width="209" ItemsSource="{Binding styles, ElementName=load_style}" SelectedIndex="0">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding name}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<ListBox Height="314" HorizontalAlignment="Left" Margin="74,297,0,0" Name="Style_subjects" VerticalAlignment="Top" Width="209" ItemsSource="{Binding SelectedItem.subjects, ElementName=all_styles}" SelectedIndex="0">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding name}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
和代码:
public class subject
{
public string name {get; set;}
public subject(string name)
{
this.name = name;
}
}
public class style
{
public string name { get; set; }
public ObservableCollection<subject> subjects {get; set;}
public style(string name)
{
this.name = name;
subjects = new ObservableCollection<subject>();
}
}
public partial class Window1 : Window
{
public ObservableCollection<style> styles {get; set;}
public Window1()
{
styles = new ObservableCollection<style>();
InitializeComponent();
styles.Add(new style("test"));
styles[0].subjects.Add(new subject("item"));
}
private void close_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
private void New_style_Click(object sender, RoutedEventArgs e)
{
styles.Add(new style("new_style"));
}
private void New_subject_Click(object sender, RoutedEventArgs e)
{
// this next line is probably not correct....
this.add(new subject("new_subject"));
}
}
答案 0 :(得分:0)
((style)this.all_styles.SelectedItem).Add(new subject("item"));