2010-12-01 4 views
12

最も一般的なWPF要件の1つでなければならないことに困惑しています。私はthis questionを読んだが、私のソリューションの実装はうまくいかない。ここでControlTemplate内のコントロールに焦点を当てる(パート2)

はlookless制御のためのマークアップです:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
       xmlns:local="clr-namespace:WpfTest"> 
    <Style TargetType="{x:Type local:CustomControl}"> 
    <Setter Property="Template"> 
     <Setter.Value> 
     <ControlTemplate TargetType="{x:Type local:CustomControl}"> 
      <Border> 
      <TextBox x:Name="myTextBox" /> 
      </Border> 
      <ControlTemplate.Triggers> 
      <Trigger Property="IsFocused" 
        Value="True"> 
       <Setter Property="FocusManager.FocusedElement" 
         Value="{Binding ElementName=myTextBox}" /> 
       <Setter TargetName="myTextBox" 
         Property="Background" 
         Value="Green" /> 
      </Trigger> 
      </ControlTemplate.Triggers> 
     </ControlTemplate> 
     </Setter.Value> 
    </Setter> 
    </Style> 
</ResourceDictionary> 

はここCustomControlのインスタンスが含まれているウィンドウのためのマークアップです:

<Window x:Class="WpfTest.Window1" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:local="clr-namespace:WpfTest" 
     Title="Window1" Height="300" Width="300"> 

    <local:CustomControl x:Name="CCtl" /> 
</Window> 

そしてここでコードビハインドです:

public partial class Window1 : Window 
{ 
    public Window1() 
    { 
     InitializeComponent(); 
     Loaded += (RoutedEventHandler)delegate { CCtl.Focus(); }; 
    } 
} 

Window1がロードされると、テキストボックスが緑色に変わります(トリグger works)しかし、フォーカスはCCtlに残り、テキストボックスには残りません。これは、次のデータエラーを表示する出力と関係があります。

Cannot find source for binding with reference 'ElementName=myTextBox'. BindingExpression:(no path); DataItem=null; target element is 'CustomControl' (Name='CCtl'); target property is 'FocusedElement' (type 'IInputElement').

このエラーがなぜ発生しているのか分かりません。感謝の意を受けてくれたすべての指導者、ありがとう。

答えて

12

ではなく、あなたのトリガのためにこれを使用してみてください:

<Trigger Property="IsFocused" Value="True"> 
    <Setter TargetName="myTextBox" Property="FocusManager.FocusedElement" Value="{Binding ElementName=myTextBox}" /> 
</Trigger> 

エラーは名前がFocusedElementプロパティが適用されている範囲ではないので、それはMyTextBoxをを見つけることができないことを語っています。この場合は、CCtlインスタンス自体にあります.CCtlインスタンス自体は、独自のテンプレート内には見えません。テンプレート内の何かにプロパティを設定することにより、Bindingは名前付き要素を見つけることができます。

+0

うん、それは本当にありがとう。 –

0

私は間違っているかもしれませんが、私はあなたの問題はあなたのプロパティトリガーと思う。

TextBoxをフォーカスするように設定すると、テンプレート親のTriggerが無効になるため、トリガーはTextBoxのフォーカスの設定を元に戻し、元に戻します。

+1

エラーメッセージは心配していませんか? –

関連する問題