日期:2014-05-18  浏览次数:20932 次

请教一个WPF问题
问题描述:

在一个UserControl里面放了一个TextBox,TextBox的初始visibility属性设为Hidden,
在UserControl的ControlTemplate.triggers中定义当UserControl获得焦点(IsFocused)时
TextBox的visibility变为visible,测试结果发现当TextBox显示后,点击textbox,光标进不去
整个控件会闪烁一下

但是如果一开始就设为visible,没有问题

代码:
UserControl1.xaml
C# code

<UserControl x:Class="WpfApplication1.UserControl1"
             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" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300"
             Focusable="True"
             MouseLeftButtonDown="UserControl_MouseLeftButtonDown">
    <UserControl.Template>
        <ControlTemplate>
            <Grid Width="100" Height="100" Background="AliceBlue">
                <TextBox Name="text" Visibility="Hidden" HorizontalAlignment="Center" VerticalAlignment="Center">123</TextBox>
            </Grid>

            <ControlTemplate.Triggers>
                <Trigger Property="IsFocused" Value="True">
                    <Setter TargetName="text" Property="Visibility" Value="Visible" />
                </Trigger>
            </ControlTemplate.Triggers>
        </ControlTemplate>
    </UserControl.Template>
        
</UserControl>




UserControl1.xaml.cs
C# code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplication1
{
    /// <summary>
    /// UserControl1.xaml 的交互逻辑
    /// </summary>
    public partial class UserControl1 : UserControl
    {
        public UserControl1()
        {
            InitializeComponent();
        }

        private void UserControl_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Focus();    
        }
    }
}



------解决方案--------------------
<Trigger Property="IsFocused" Value="True">
<Setter TargetName="text" Property="Visibility" Value="Visible" />
</Trigger>
焦点只能有一个吧