WPF UserControl组合框设置SelectedValue并引发ChangeEvent

本文关键字:ChangeEvent SelectedValue 设置 UserControl 组合 WPF | 更新日期: 2023-09-27 17:59:12

我对WPF比较陌生,因此存在一些问题。

我需要UserControls,但我在一个包含ComboBox的控件上遇到了问题。我需要在Initialization中设置Value,但它不起作用。我需要将ChangedEvent路由到MainWindow。

我的UserControl XAML:

<UserControl x:Class="xyz.FileLineDropBox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
Name="UC">
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="30" />
        <ColumnDefinition Width="110" />
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="30" />
    </Grid.ColumnDefinitions>
    <Label Grid.Column="1" VerticalAlignment="Center" Content="{Binding ElementName=UC, Path=Description}" />
    <ComboBox Grid.Column="2" VerticalAlignment="Center" HorizontalAlignment="Left" Width="40" SelectionChanged="valueChangedEventHandler" SelectedItem="Value">
        <!-- simple Alternative to Spin / NumericUpDown -->
        <ComboBoxItem Content="1" />
        <ComboBoxItem Content="2" />
        <ComboBoxItem IsSelected="True" Content="3" />
        <ComboBoxItem Content="4" />
    </ComboBox>
</Grid>

代码背后的我的用户控制:

namespace xyz{
public partial class FileLineDropBox : UserControl {
    ...
    //Description///////////////////////////////////////////////////////////
    public string Description{
        get { return (string)GetValue(DescriptionProperty); }
        set { SetValue(DescriptionProperty, value); }
    }
    public static readonly DependencyProperty DescriptionProperty = DependencyProperty.Register("Description", typeof(string), typeof(FileLineDropBox), new UIPropertyMetadata(""));
    //Value/////////////////////////////////////////////////////////////////
    public string Value{
        get { return (string)GetValue(ValueProperty); }
        set { SetValue(ValueProperty, value); }
    }
    public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(string), typeof(FileLineDropBox), new UIPropertyMetadata(""));
    ////////////////////////////////////////////////////////////////////////
    // Eventhandler (Text / Selection changed)
    private void valueChangedEventHandler(object sender, SelectionChangedEventArgs e){
        SelectionChangedEventArgs args = new SelectionChangedEventArgs(ValueChangedEvent, e.RemovedItems, e.AddedItems);
        RaiseEvent(args);
    }
    ////////////////////////////////////////////////////////////////////////
    // Routing the EventHandler up to the MainWindow
    public static readonly RoutedEvent ValueChangedEvent = EventManager.RegisterRoutedEvent("ValueChangedEvent", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(FileLineDropBox));
    public event SelectionChangedEventHandler ValueChanged{
        add { AddHandler(ValueChangedEvent, value); }
        remove { RemoveHandler(ValueChangedEvent, value); }
    }
}

在代码后面的主窗口中,我想设置值,但它没有链接到所需的值(选择)。EventHandler的添加导致执行时出错:

    public partial class MainWindow : Window {
    FileLineDropBox     myLineDropBox;
    public MainWindow() {
        ...
        Init3_CodedComponents();
        myLineDropBox.Value                     = "4";
    }
    private void Init3_CodedComponents(){
        AddHandler(FileLineDropBox.ValueChangedEvent, new SelectionChangedEventHandler(FileLineComboBox_CntChangedEvent));  // Abo of EventHandler from FileLine
        ...
        myLineDropBox                           = new FileLineDropBox();
        myLineDropBox.Description               = "blub";
        myGrids[1].Children.Add(myLineDropBox);
        myGrids[1].RowDefinitions.Add(new RowDefinition());
        Grid.SetRow(myLineDropBox, linePos);
        ...
    }
    ...
    private void FileLineComboBox_CntChangedEvent(object sender, SelectionChangedEventArgs e){
        if(!isInitialized)return;
        ComboBox myCb = sender as ComboBox;
        int maxId;
        string sMaxId = (e.AddedItems[0] as ComboBoxItem).Content as string;
        int.TryParse(sMaxId, out maxId);
        ...
    }
}

编辑,第一个问题的解决方案如下:

  1. 在XAML中更改:

    <组合框网格。Column="2"…Name="FileLineCB"/>

  2. 从代码后面删除了值绑定代码

  3. 添加在代码后面:

    public void CB_Add_Item(string NewItem) {
        this.FileLineCB.Items.Add(NewItem);
    }
    public void CB_Select_Item(string SelectThis) {
        this.FileLineCB.SelectedItem = SelectThis;
    }
    

WPF UserControl组合框设置SelectedValue并引发ChangeEvent

问题已经解决,但可能不是最好的方法。如果有更好或更推荐的方式,请在这里添加。

以下是我的解决方案:XAML

<UserControl x:Class="xyz.FileLineDropBox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
Name="UC">
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="30" />
        <ColumnDefinition Width="110" />
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="30" />
    </Grid.ColumnDefinitions>
    <Label Grid.Column="1" VerticalAlignment="Center" Content="{Binding ElementName=UC, Path=Description}" />
    <ComboBox Grid.Column="2" VerticalAlignment="Center" HorizontalAlignment="Left" Width="40" Name="FileLineCB" SelectedItem="{Binding ElementName=UC, Path=Value}" SelectionChanged="valueChangedEventHandler" />
</Grid>

代码背后:

namespace xyz {
public partial class FileLineDropBox : UserControl {
    ...
    //Changing ComboBox/////////////////////////////////////////////////////
    public void CB_Add_Item(string NewItem) {
        this.FileLineCB.Items.Add(NewItem);
    }
    public void CB_Select_Item(string SelectThis) {
        this.FileLineCB.SelectedItem = SelectThis;
    }
    //Value/////////////////////////////////////////////////////////////////
    public string Value{
        get { return (string)GetValue(ValueProperty); }
        set { SetValue(ValueProperty, value); }
    }
    public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(string), typeof(FileLineDropBox), new UIPropertyMetadata(""));
    ////////////////////////////////////////////////////////////////////////
    // Eventhandler (Text / Selection changed)
    private void valueChangedEventHandler(object sender, RoutedEventArgs e){
        RaiseEvent(new RoutedEventArgs(FileLineDropBox.ValueChangedEvent));
    }
    ////////////////////////////////////////////////////////////////////////
    // Routing the EventHandler up to the MainWindow
    public static readonly RoutedEvent ValueChangedEvent = EventManager.RegisterRoutedEvent("ValueChangedEvent", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(FileLineDropBox));
    public event RoutedEventHandler ValueChanged{
        add { AddHandler(ValueChangedEvent, value); }
        remove { RemoveHandler(ValueChangedEvent, value); }
    }
}

}

主窗口:

    //init
    private void Init3_CodedComponents(){
        myLineDropBox.CB_Add_Item("1");
        myLineDropBox.CB_Add_Item("2");
        ...
        myLineDropBox.CB_Select_Item("4");
        ...
        AddHandler(FileLineDropBox.ValueChangedEvent, new RoutedEventHandler(FileLineComboBox_CntChangedEvent));
    }
    // EventHandler
    private void FileLineComboBox_CntChangedEvent(object sender, RoutedEventArgs e){
        ...
        int.TryParse(myLineDropBox.Value, out maxId);
        ...
    }