简体   繁体   English

WPF UserControl ComboBox设置SelectedValue并引发ChangeEvent

[英]WPF UserControl ComboBox set SelectedValue and raise ChangeEvent

I'm relatively new to WPF and so there are some Problems. 我对WPF比较陌生,因此存在一些问题。

I need UserControls and I have a trouble with one which contains a ComboBox. 我需要UserControls,但其中一个包含ComboBox的应用程序出现了问题。 I need to set the Value within Initialisation, but it doesn't work. 我需要在初始化中设置值,但是它不起作用。 And I need the ChangedEvent routed to the MainWindow. 而且我需要将ChangedEvent路由到MainWindow。

My UserControl-XAML: 我的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>

My UserControl-Behind-Code: 我的UserControl背后代码:

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); }
    }
}

In MainWindow-Behind-Code I want to set the Value, but it is not linked to the wanted Value (Selection). 在MainWindow-Behind-Code中,我想设置值,但未链接到所需的值(选择)。 And the Adding of the EventHandler causes an Error while Executing: 并且在执行过程中添加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);
        ...
    }
}

Edit, Solution for first Problem is following: 编辑,第一个问题的解决方案如下:

  1. changed in XAML: XAML中的更改:

    <ComboBox Grid.Column="2" ... Name="FileLineCB" ... /> <ComboBox Grid.Column =“ 2” ... Name =“ FileLineCB” ... />

  2. removed Value-Binding-Code from Behind Code 从隐藏代码中删除了Value-Binding-Code

  3. added in Behind-Code: 在背后代码中添加:

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

Problems solved, but maybe not the best Way. 问题解决了,但也许不是最好的方法。 If one has a better or more recommended Way, pls add this here. 如果有更好或更推荐的方式,请在此处添加。

Here is my Solution: XAML 这是我的解决方案: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>

Behind-Code: 幕后代码:

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); }
    }
}

} }

MainWindow: 主窗口:

    //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);
        ...
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM