点击编辑控件 - 怎么做?

时间:2010-11-01 08:24:05

标签: silverlight silverlight-4.0

我正在使用Silverlight 2.0 Unleashed + Silverlight 4.0 Unleashed学习Silverlight,好吧,只是弄乱它: - )

作为其中的一部分,我正在尝试开发一个非常简单的内容控件:可以通过单击来编辑的标签。

我从另一个问题(Click-to-edit in Silverlight)中获取了灵感,但我遇到了一些与我对Silverlight不熟悉的问题。 :)

我会首先发布代码,然后是我的问题。

这是我的XAML:

<ContentControl x:Class="MyTestProject.SilverlightControl1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:sdk="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data.Input" xmlns:local="clr-namespace:MyTestProject" mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">
    <ContentControl.Resources>
        <ControlTemplate x:Key="EditableLabelTextboxTemplate">
            <TextBox Name="UCTB" Text="{Binding Text, Mode=TwoWay}" Width="100" Height="25" ></TextBox>
        </ControlTemplate>
        <ControlTemplate x:Name="LabelTemplate" TargetType="local:SilverlightControl1">
            <sdk:Label x:Name="UCLBL" Content="{Binding Text}" />
        </ControlTemplate>
        <Style TargetType="local:SilverlightControl1">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate x:Name="LabelTemplate2" TargetType="local:SilverlightControl1">
                        <sdk:Label x:Name="UCLBL" Content="{Binding Text}" />
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </ContentControl.Resources>
</ContentControl>

这是我的CodeBehind:

public partial class SilverlightControl1 : ContentControl
    {
        public string Text { get; set; }

        public SilverlightControl1()
        {
            this.DataContext = this;
            Text = "Hello, World!";
            this.DefaultStyleKey = typeof(SilverlightControl1);
            //Template = this.Resources["LabelTemplate"] as ControlTemplate;
            InitializeComponent();
        }

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            this.MouseLeftButtonDown += HandleLabelLeftMouseDown;
            this.KeyDown += HandleTextboxEnter;
        }

        public static void HandleTextboxEnter(object sender, KeyEventArgs args)
        {
            var ctrl = sender as SilverlightControl1;
            if (ctrl.Template == ctrl.Resources["EditableLabelTextboxTemplate"])
            {
                if (args.Key == Key.Enter)
                {
                    ctrl.Template = ctrl.Resources["LabelTemplate"] as ControlTemplate;
                }
            }
        }

        public static void HandleLabelLeftMouseDown(object sender, MouseButtonEventArgs args)
        {
            var editableLabel = sender as SilverlightControl1;
            if (editableLabel.Template != editableLabel.Resources["EditableLabelTextboxTemplate"])
            {
                editableLabel.Template = editableLabel.Resources["EditableLabelTextboxTemplate"] as ControlTemplate;
            }
        }
    }

首先,我必须实例化我的控件的方式非常笨拙和冗余。

有两个ControlTemplates(一个标签,一个文本框)但是还有一个带有标签的Style用于初始化。如果我删除它(以及代码隐藏中的构造函数中的correspoding行),即使我也设置了模板,也不会呈现任何内容。必须有更好的方法吗?

我的第二个问题是,当我将控件放在测试项目中并使用它时,控件移动?它将从中间的左侧开始作为标签,然后我点击它,文本框显示在页面的中心,然后输入标签重新出现在屏幕的左侧?

编辑: 第三,一旦我用文本框替换标签,文本框就没有焦点,我无法弄清楚如何将它赋予它?

最后,现在停止编辑的唯一方法是点击“输入”。理想情况下,我只想在文本框外单击,但使用丢失的焦点事件(如链接中所示)似乎常常让我能够使用它?

我希望有一些Silverlight大师可以帮助我! : - )

哦,如果有人知道点击编辑控件我可以使用/看看,我也非常感激:)

提前致谢!

1 个答案:

答案 0 :(得分:4)

我希望我能帮到你。你需要的是一个TextBox,它在开始时是不可编辑的,但如果你点击它,它就是可编辑的。

为此,我创建了一个继承自TextBox的控件(我使用了vs模板TemplatedControl)。我添加了两个状态(Edit和NotEdit)和一个Rectangle,它作为非编辑模式的文本层(为了防止在鼠标上方改变鼠标光标)。我也在边界做了一些任务。例如。在非编辑状态中,边框的大小为0,因此TextBox看起来像Label。

这是xaml:

<Style TargetType="local:ClickToEditTextBox">
            <Setter Property="BorderThickness" Value="1"/>
            <Setter Property="Background" Value="#FFFFFFFF"/>
            <Setter Property="Foreground" Value="#FF000000"/>
            <Setter Property="Padding" Value="2"/>
            <Setter Property="BorderBrush">
                <Setter.Value>
                    <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                        <GradientStop Color="#FFA3AEB9" Offset="0"/>
                        <GradientStop Color="#FF8399A9" Offset="0.375"/>
                        <GradientStop Color="#FF718597" Offset="0.375"/>
                        <GradientStop Color="#FF617584" Offset="1"/>
                    </LinearGradientBrush>
                </Setter.Value>
            </Setter>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="local:ClickToEditTextBox">
                        <Grid x:Name="RootElement">
                            <VisualStateManager.VisualStateGroups>
                                <VisualStateGroup x:Name="CommonStates">
                                    <VisualState x:Name="Normal"/>
                                    <VisualState x:Name="MouseOver"/>
                                    <VisualState x:Name="Disabled">
                                        <Storyboard>
                                            <DoubleAnimation Storyboard.TargetName="DisabledVisualElement" Storyboard.TargetProperty="Opacity" To="1" Duration="0"/>
                                        </Storyboard>
                                    </VisualState>
                                    <VisualState x:Name="ReadOnly">
                                        <Storyboard>
                                            <DoubleAnimation Storyboard.TargetName="ReadOnlyVisualElement" Storyboard.TargetProperty="Opacity" To="1" Duration="0" />
                                        </Storyboard>
                                    </VisualState>
                                </VisualStateGroup>
                                <VisualStateGroup x:Name="FocusStates">
                                    <VisualState x:Name="Focused">
                                        <Storyboard>
                                            <DoubleAnimation Storyboard.TargetName="FocusVisualElement" Storyboard.TargetProperty="Opacity" To="1" Duration="0"/>
                                        </Storyboard>
                                    </VisualState>
                                    <VisualState x:Name="Unfocused">
                                        <Storyboard>
                                            <DoubleAnimation Storyboard.TargetName="FocusVisualElement" Storyboard.TargetProperty="Opacity" To="0" Duration="0"/>
                                        </Storyboard>
                                    </VisualState>
                                </VisualStateGroup>
                                <VisualStateGroup x:Name="ValidationStates">
                                    <VisualState x:Name="Valid"/>
                                    <VisualState x:Name="InvalidUnfocused">
                                        <Storyboard>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ValidationErrorElement" Storyboard.TargetProperty="Visibility">
                                                <DiscreteObjectKeyFrame KeyTime="0">
                                                    <DiscreteObjectKeyFrame.Value>
                                                        <Visibility>Visible</Visibility>
                                                    </DiscreteObjectKeyFrame.Value>
                                                </DiscreteObjectKeyFrame>
                                            </ObjectAnimationUsingKeyFrames>
                                        </Storyboard>
                                    </VisualState>
                                    <VisualState x:Name="InvalidFocused">
                                        <Storyboard>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ValidationErrorElement" Storyboard.TargetProperty="Visibility">
                                                <DiscreteObjectKeyFrame KeyTime="0">
                                                    <DiscreteObjectKeyFrame.Value>
                                                        <Visibility>Visible</Visibility>
                                                    </DiscreteObjectKeyFrame.Value>
                                                </DiscreteObjectKeyFrame>
                                            </ObjectAnimationUsingKeyFrames>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetName="validationTooltip" Storyboard.TargetProperty="IsOpen">
                                                <DiscreteObjectKeyFrame KeyTime="0">
                                                    <DiscreteObjectKeyFrame.Value>
                                                        <sys:Boolean>True</sys:Boolean>
                                                    </DiscreteObjectKeyFrame.Value>
                                                </DiscreteObjectKeyFrame>
                                            </ObjectAnimationUsingKeyFrames>
                                        </Storyboard>
                                    </VisualState>
                                </VisualStateGroup>
                                <!-- The new edit states -->
                                <VisualStateGroup x:Name="EditStates">
                                    <VisualState x:Name="Edit">
                                        <Storyboard>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)" Storyboard.TargetName="rectangle">
                                                <DiscreteObjectKeyFrame KeyTime="0">
                                                    <DiscreteObjectKeyFrame.Value>
                                                        <Visibility>Collapsed</Visibility>
                                                    </DiscreteObjectKeyFrame.Value>
                                                </DiscreteObjectKeyFrame>
                                            </ObjectAnimationUsingKeyFrames>
                                        </Storyboard>
                                    </VisualState>
                                    <VisualState x:Name="NotEdit">
                                        <Storyboard>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(Border.BorderThickness)" Storyboard.TargetName="Border">
                                                <DiscreteObjectKeyFrame KeyTime="0">
                                                    <DiscreteObjectKeyFrame.Value>
                                                        <Thickness>0</Thickness>
                                                    </DiscreteObjectKeyFrame.Value>
                                                </DiscreteObjectKeyFrame>
                                            </ObjectAnimationUsingKeyFrames>
                                        </Storyboard>
                                    </VisualState>
                                </VisualStateGroup>
                            </VisualStateManager.VisualStateGroups>
                            <Border x:Name="Border" CornerRadius="1" Opacity="1" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="1">
                                <Grid>
                                    <Border x:Name="ReadOnlyVisualElement" Opacity="0" Background="#5EC9C9C9"/>
                                    <Border x:Name="MouseOverBorder" BorderThickness="1" BorderBrush="Transparent">
                                        <Grid>
                                            <ScrollViewer x:Name="ContentElement" Padding="{TemplateBinding Padding}" BorderThickness="0" IsTabStop="False"/>
                                            <Rectangle x:Name="rectangle" Fill="#02FFFFFF" />
                                        </Grid>
                                    </Border>
                                </Grid>
                            </Border>
                            <Border x:Name="DisabledVisualElement" Background="#A5F7F7F7" BorderBrush="#A5F7F7F7" BorderThickness="{TemplateBinding BorderThickness}" Opacity="0" IsHitTestVisible="False"/>
                            <Border x:Name="FocusVisualElement" BorderBrush="#FF6DBDD1" BorderThickness="{TemplateBinding BorderThickness}" Margin="1" Opacity="0" IsHitTestVisible="False"/>
                            <Border x:Name="ValidationErrorElement" BorderThickness="1" CornerRadius="1" BorderBrush="#FFDB000C" Visibility="Collapsed">
                                <ToolTipService.ToolTip>
                                    <ToolTip x:Name="validationTooltip" Template="{StaticResource ValidationToolTipTemplate}" Placement="Right" 
                         PlacementTarget="{Binding RelativeSource={RelativeSource TemplatedParent}}"
                         DataContext="{Binding RelativeSource={RelativeSource TemplatedParent}}">
                                        <ToolTip.Triggers>
                                            <EventTrigger RoutedEvent="Canvas.Loaded">
                                                <BeginStoryboard>
                                                    <Storyboard>
                                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="validationTooltip" Storyboard.TargetProperty="IsHitTestVisible">
                                                            <DiscreteObjectKeyFrame KeyTime="0">
                                                                <DiscreteObjectKeyFrame.Value>
                                                                    <sys:Boolean>true</sys:Boolean>
                                                                </DiscreteObjectKeyFrame.Value>
                                                            </DiscreteObjectKeyFrame>
                                                        </ObjectAnimationUsingKeyFrames>
                                                    </Storyboard>
                                                </BeginStoryboard>
                                            </EventTrigger>
                                        </ToolTip.Triggers>
                                    </ToolTip>
                                </ToolTipService.ToolTip>
                                <Grid Width="12" Height="12" HorizontalAlignment="Right" Margin="1,-4,-4,0" VerticalAlignment="Top" Background="Transparent">
                                    <Path Margin="1,3,0,0" Data="M 1,0 L6,0 A 2,2 90 0 1 8,2 L8,7 z" Fill="#FFDC000C"/>
                                    <Path Margin="1,3,0,0" Data="M 0,0 L2,0 L 8,6 L8,8" Fill="#ffffff"/>
                                </Grid>
                            </Border>
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

如您所见,有两种新状态,Edit和NotEdit。

所以在后面的代码中,我将控件初始化“发送”到NotEdit状态,并为GotFocus和LostFocus添加两个处理程序。

this.GotFocus += ClickToEditTextBox_GotFocus;
this.LostFocus += ClickToEditTextBox_LostFocus;
VisualStateManager.GoToState(this, "NotEdit", false);

处理程序只是在定义的状态下“发送”控件:

void ClickToEditTextBox_LostFocus(object sender, RoutedEventArgs e)
        {
            VisualStateManager.GoToState(this, "NotEdit", false);
        }

        void ClickToEditTextBox_GotFocus(object sender, RoutedEventArgs e)
        {
            VisualStateManager.GoToState(this, "Edit", false);
        }

这是完整的src代码:

public class ClickToEditTextBox : TextBox
    {
        public ClickToEditTextBox()
        {
            this.DefaultStyleKey = typeof(ClickToEditTextBox);
        }

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            this.GotFocus += ClickToEditTextBox_GotFocus;
            this.LostFocus += ClickToEditTextBox_LostFocus;

            VisualStateManager.GoToState(this, "NotEdit", false);

        }

        void ClickToEditTextBox_LostFocus(object sender, RoutedEventArgs e)
        {
            VisualStateManager.GoToState(this, "NotEdit", false);
        }

        void ClickToEditTextBox_GotFocus(object sender, RoutedEventArgs e)
        {
            VisualStateManager.GoToState(this, "Edit", false);
        }
    }

现在您可以在UserControl中使用它了:

<SilverlightApplication1:ClickToEditTextBox Text="12345" Width="100" Height="22" />

这只是一个快速实现,因此可以进行一些改进。但我希望,这可以帮助您解决问题。

BR,TJ