通过单击wpf动态更改控件

时间:2019-03-11 13:43:51

标签: c# wpf xaml

我想在WPF中实现某种行为。我四处寻找安静的时间,并决定对帮助进行排序。我要实现以下行为。

我有一个TextBlock和一个ComboBox彼此叠置。我希望在ComboBox被聚焦时出现TextBlock。同样,ComboBox的作品完成后(例如,选择ComboBoxItem)。我想回到我的旧视图(即顶部的TextBlock)。任何人都可以展示这种行为的示例,或者只是指导我一些事情。

我有一个ZIndex方法,如下所示。

<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>

以及背后的代码

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

1 个答案:

答案 0 :(得分:1)

不确定我是否正确地理解了您的需求,但这就是我想您想要的:

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