简体   繁体   中英

Changing controls dynamically by clicking wpf

I want to implement a certain behaviour in WPF. I searched around for quiet a long time and decided to sort the help. I want to attain the following behaviour.

I have a TextBlock and a ComboBox lying on top of each other. I want the ComboBox to appear when the TextBlock is being focused. Also once the works with ComboBox are finished (eg ComboBoxItem is selected). I want to get back to my older view (ie the TextBlock on top). Can anybody show a sample of this behaviour or just guide me with something.

I have a ZIndex method which I have tried as below.

<Grid>  
    <Button Name="Button1" Canvas.ZIndex="4" Content="Button1" Canvas.Top="100" Width="163" Height="58" FontSize="26" Click="Button1_Click" />  
    <Button Name="Button2" Canvas.ZIndex="3" Content="Button2" Canvas.Top="100" Canvas.Left="130" Width="163" Height="58" FontSize="26" Click="Button2_Click"  />
</Grid>

And the code behind

private void Button1_Click(object sender, RoutedEventArgs e)
{
    Canvas.SetZIndex(sender as UIElement, 1);
}
private void Button2_Click(object sender, RoutedEventArgs e)
{
    Canvas.SetZIndex(sender as UIElement, 0);
}

Not sure if i correctly undestand your need exactly but this is what i think you want:

XAML:

        <Grid Width="50">
            <ComboBox x:Name="cb" SelectedIndex="0" ItemsSource="{Binding MyObservableCollection}"/>
            <TextBox x:Name="tb" Text="{Binding ElementName=cb,Path=SelectedItem}">
                <TextBox.Style>
                    <Style TargetType="TextBox">
                        <Style.Triggers>
                            <DataTrigger Binding="{Binding ElementName=tb, Path=IsFocused}" Value="true">
                                <Setter Property="Visibility" Value="Hidden"/>
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                </TextBox.Style>
            </TextBox>
        </Grid>

DataContext:

    private ObservableCollection<string> myObservableCollection = new ObservableCollection<string>{ "one", "two", "tree" };

    public ObservableCollection<string> MyObservableCollection
    {
        get => this.myObservableCollection;
        set => SetField(ref this.myObservableCollection, value);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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