在 WPF 中,根据组合框输入创建扩展器

In WPF, create expander based on combobox input

我正在使用这个示例来解决一个更大的问题,但由于我是 wpf 和 C# 的新手,我必须从某个地方开始,对吗?好吧,我想做的是基于组合框输入创建一个新的扩展器。我目前的代码非常简单。

MainWindow.xaml

<!-- MainWindow.xaml -->
<Grid>
    <StackPanel>
        <ComboBox IsEditable="True" IsReadOnly="True" Text="Default Text" HorizontalAlignment="Left" Width="260" Height="30">
            <ComboBoxItem PreviewMouseLeftButtonDown="method1" Name="method1>1</ComboBoxItem>
            <ComboBoxItem PreviewMouseLeftButtonDown="method2" Name="method1>2</ComboBoxItem>
            <ComboBoxItem PreviewMouseLeftButtonDown="method3" Name="method1>3</ComboBoxItem>
            <ComboBoxItem PreviewMouseLeftButtonDown="method4" Name="method1>4</ComboBoxItem>
        </ComboBox>
    </StackPanel>
</Grid>

MainWindow.xaml.cs

//MainWindow.xaml.cs
Public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }
    private void method1(object sender, MouseEventArgs e)
    {
        MessageBox.Show("method1");
    }

    private void method2(object sender, MouseEventArgs e)
    {
        MessageBox.Show("method2");
    }

    private void method3(object sender, MouseEventArgs e)
    {
        MessageBox.Show("method3");
    }

    private void method4(object sender, MouseEventArgs e)
    {
        MessageBox.Show("method4");
    }
    //public class dynamicExpanderCreation
    //{
        //Here's where I'm assuming the class for dynamic creation should go.      
    //}

我想让他们创建一个基于组合框的 selection 创建的扩展器,而不是每个人都调用一个方法。例如,如果您要 select 3,则扩展器会出现在左侧,标记为 3。然后如果您 select 1,则扩展器会出现在 #3 扩展器下方,标记为 1。

我猜您在 MainWindow.xaml.cs 文件中创建了一个 class,并为组合框的每个 selection 创建了一个扩展器的新实例。根据我非常简单的任务,我发现了一些对我来说太复杂而无法遵循的示例。我看过的例子是 here, here, and here

我并不是说这些例子不好,只是以我的经验水平,我无法让它们中的任何一个工作。感谢任何帮助。

In WPF you need to put any of the panels like stackpanel/wrappanel/dockpanel/Grid

<ComboBox Name="combobox" IsEditable="False" SelectionChanged="ComboBox_SelectionChanged" Text="Default Text" HorizontalAlignment="Left" Width="260" Height="30">
                <ComboBoxItem>1</ComboBoxItem>
                <ComboBoxItem>2</ComboBoxItem>
                <ComboBoxItem>3</ComboBoxItem>
                <ComboBoxItem>4</ComboBoxItem>
            </ComboBox>

            <StackPanel Name="dock">                   

            </StackPanel>

And in the Codebehind

private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var itemIndex = combobox.SelectedItem;
            Expander expander = new Expander();
            dock.Children.Add(expander);
        }

Where dock is the name of your panel

希望对您有所帮助。