好吧,很明顯,還有更多,但這裏的基礎知識。這看起來很簡單,但不起作用。TextBox.Focus()只有在我有一個MessageBox.Show()後纔有效?
我有一個標籤。 我有一個文本框。
標籤=「1」 TextBox的Z-索引的Z-索引=「0」
即它們是在彼此的頂部和文本框是不可見的。
當用戶點擊LABEL(現在通過PreviewMouseLeftButtonDown,但在此作品後將成爲ViewModel中的命令),應用程序應該將焦點設置到TextBox。
簡單吧?錯...
如果我有這個代碼...它不起作用。
private void inVisTxtBox_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
inVisTxtBox.Focus();
// TextBox_MouseDown(sender, e);
}
如果我有這樣的代碼......它的工作
private void inVisTxtBox_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
inVisTxtBox.Focus();
// TextBox_MouseDown(sender, e);
MessageBox.Show("This is ridiculous");
}
最後的XAML:
<Ctrls:AControl x:Class="<location of class>"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:CommandControls="clr-namespace:<location of custom controls>" VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
<Grid Margin="0,15,15,15">
<!--<Button Height="50" Click="Button_Click">FOC</Button>-->
<TextBox x:Name="inVisTxtBox" Focusable="True" Grid.ZIndex="0" Width="100" Margin="5"/>
<Label Grid.ZIndex="1" Margin="5" Content="243234234234234" HorizontalAlignment="Left" Width="100" PreviewMouseLeftButtonDown="inVisTxtBox_PreviewMouseLeftButtonDown"
x:Name="KeyPress_TextBox"/>
</Grid>
</Ctrls:AControl>
編輯
如果我使標籤進入作爲它的模板,它帶有標籤的模板按鈕:
<Button x:Name="KeyPress_TextBox" Grid.ZIndex="1" Margin="5" Content="243234234234234" HorizontalAlignment="Left" Width="100" Click="KeyPress_TextBox_Click">
<Button.Template>
<ControlTemplate TargetType="Button">
<Label Content="{TemplateBinding Content}"/>
</ControlTemplate>
</Button.Template>
</Button>
這是爲什麼?
必須與事件路由/泡泡的方式有關嗎?
我現在正在通過這樣做,但我更好奇發生了什麼。
而且......沒有下面的作品之一:
Keyboard.Focus(inVisTxtBox);
FocusManager.SetFocusedElement(MainGrid,inVisTxtBox);
Keyboard.Focus(inVisTxtBox);
你提到TextBox是不可見的?這是爲什麼?並且如果它實際上是隱形的,那麼在沒有實際使其可見的情況下聚焦它的意義何在? – hndr
它本身不是「隱形」的。它在標籤後面。原因是我正在創建一個「Key Press」控件,它不會有焦點,但會顯示用戶輸入的內容。示例:1.用戶單擊標籤。 2. TextBox獲得焦點。 3.用戶開始輸入。 4.標籤綁定到TextBox Text屬性。 5.標籤更新但用戶看不到閃爍的光標等。 – tronious
現在我很困惑。但是,如果你所要做的只是「點擊標籤時將焦點設置到文本框」,那麼上面的代碼應該可以工作,不需要消息框。你確定你在正確的地方設置了活動嗎?從事件處理程序的名稱來看,它似乎是爲TextBox生成的。 – hndr