2013-07-01 25 views
0

我創建了一個自定義WPF控件,該控件顯示屬於int的Weight屬性的值。當用戶點擊自定義控件或當控件獲得焦點時,用戶應該能夠編輯Weight屬性的值。如何使自定義控件的值在接收焦點時可編輯

要做到這一點,我試過如下:

  • 如果控制是「無效」,Weight屬性將在TextBlock中顯示 。
  • 如果控件獲得焦點,則Weight屬性 將顯示在文本框中。

    <ResourceDictionary 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:local="clr-namespace:WpfCustomControlLibrary1"> 
    
    <Style TargetType="{x:Type local:CustomControl1}"> 
        <Style.Resources> 
         <ControlTemplate x:Key="Control_Focused" > 
          <Border Background="Green" 
             BorderBrush="Black" 
             CornerRadius="50" Width="40" Height="40"> 
           <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center"> 
            <TextBox Width="35" 
               Text="{Binding Mode=TwoWay,Path=Model.Weight,UpdateSourceTrigger=PropertyChanged,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type local:CustomControl1}} 
               ,Converter={x:Static local:CustomControl1.IntToStringConverter}}" /> 
    
           </StackPanel> 
          </Border> 
         </ControlTemplate> 
    
         <ControlTemplate x:Key="Control"> 
          <Border Background="Green" 
             BorderBrush="Black" 
             CornerRadius="50" Width="40" Height="40"> 
           <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center"> 
            <TextBlock x:Name="PART_TextBlockWeighted" Text="{Binding Mode=TwoWay,Path=Model.Weight,UpdateSourceTrigger=PropertyChanged,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type local:CustomControl1}}}" 
               HorizontalAlignment="Center" VerticalAlignment="Center" /> 
           </StackPanel> 
          </Border> 
         </ControlTemplate> 
    
    
        </Style.Resources> 
        <Style.Triggers> 
         <Trigger Property="IsFocused" Value="True"> 
          <Setter Property="Template" Value="{StaticResource Control_Focused}" ></Setter> 
         </Trigger> 
         <Trigger Property="IsFocused" Value="False"> 
          <Setter Property="Template" Value="{StaticResource Control}" ></Setter> 
         </Trigger> 
        </Style.Triggers> 
    
    </Style> 
    

這種自定義控件風格的問題是,當用戶點擊到文本框,觸發將控件模板改變到TextBlock。我怎樣才能解決這個問題?

+0

爲什麼不只是使用單個文本框,並將IsReadOnly =「True」設置爲不可編輯,如果需要,也可以爲其提供不同的樣式。 – Viv

回答

0

請嘗試使用IsKeyboardFocusWithin屬性。我相信這會做你需要的。

<Style.Triggers> 
    <Trigger Property="IsKeyboardFocusWithin" Value="True"> 
     <Setter Property="Template" Value="{StaticResource Control_Focused}" ></Setter> 
    </Trigger> 
    <Trigger Property="IsKeyboardFocusWithin" Value="False"> 
     <Setter Property="Template" Value="{StaticResource Control}" ></Setter> 
    </Trigger> 
</Style.Triggers> 
相關問題