为了账号安全,请及时绑定邮箱和手机立即绑定

如何将按钮和组合框放在一起

如何将按钮和组合框放在一起

C#
12345678_0001 2023-09-16 17:45:08
我想要一个带有按钮的组合框,如下所示:因为我想使用它,以便可以选择项目并将其添加到 ListView。问题:我不知道如何获取按钮中的图标,如图所示如何让它们很好地排列在一起,或者有没有办法将我不知道的两个元素结合起来?
查看完整描述

1 回答

?
泛舟湖上清波郎朗

TA贡献1818条经验 获得超3个赞

这是一个工作示例。


假设您的用户控件有两个控件;一个ComboBox和一个Button。您希望能够将主控件(父控件)中的某些内容绑定到用户控件。然后,在选择某些内容并单击按钮后,您希望用户控件将事件发生通知给父级,并传递所选值。


用户控件XAML:


<UserControl ...

             d:DesignHeight="40" d:DesignWidth="200">

    <Grid>

        <Grid.ColumnDefinitions>

            <ColumnDefinition Width="160"/>

            <ColumnDefinition Width="40"/>

        </Grid.ColumnDefinitions>


        <ComboBox Grid.Column="0" Margin="4" Name="ItemsComboBox"

                  ItemsSource="{Binding Source, RelativeSource={RelativeSource AncestorType=UserControl}}"/>

        <Button Grid.Column="1" Margin="4" Content="+"

                Click="Button_Click"/>

    </Grid>

</UserControl>

以下绑定将允许您将数据列表绑定到组合框(形成父级):


ItemsSource="{Binding Source, RelativeSource={RelativeSource AncestorType=UserControl}}"

在您的 中MainWindow,您将像这样使用该控件:


<Grid>

    <local:UCComboButton Grid.Row="0" Width="200" Height="40" x:Name="MyUC"

                         Source="{Binding Names}"/>

</Grid>

并在UserControl后面的s代码中:


public partial class UCComboButton : UserControl

{

    public UCComboButton()

    {

        InitializeComponent();

    }


    // We use this dependency property to bind a list to the combo box.

    public static readonly DependencyProperty SourceProperty = DependencyProperty.Register("Source", typeof(IEnumerable), typeof(UCComboButton), new PropertyMetadata(null));


    public IEnumerable Source

    {

        get { return (IEnumerable)GetValue(SourceProperty); }

        set { SetValue(SourceProperty, value); }

    }


    // This is to send the occurred event, in this case button click, to the parent, along with the selected data.

    public class SelectedItemEventArgs : EventArgs

    {

        public string SelectedChoice { get; set; }

    }


    public event EventHandler<SelectedItemEventArgs> ItemHasBeenSelected;


    private void Button_Click(object sender, RoutedEventArgs e)

    {

        var selected = ItemsComboBox.SelectedValue;

        ItemHasBeenSelected?.Invoke(this, new SelectedItemEventArgs { SelectedChoice = selected.ToString() });

    }

}

现在在MainWindow.xaml.cs:


public MainWindow()

{

    InitializeComponent();

    // Subscribe to the item selected event

    MyUC.ItemHasBeenSelected += UCButtonClicked;


    Names = new List<string>

    {

        "A",

        "B",

        "C"

    };


    DataContext = this;

}


void UCButtonClicked(object sender, UCComboButton.SelectedItemEventArgs e)

{

    var value = e.SelectedChoice;

    // Do something with the value

}

请注意,上面的Names列表是从主窗口绑定到用户控件的内容XAML。


查看完整回答
反对 回复 2023-09-16
  • 1 回答
  • 0 关注
  • 49 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信