有没有办法使用 WPF Trigger
将 Focus
从一个控件设置到另一个控件?
像下面的例子:
<Page
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBox Name="txtName"></TextBox>
<TextBox Grid.Row="1" Name="txtAddress"></TextBox>
<Button Grid.Row="2" Content="Finish">
<Button.Triggers>
<EventTrigger RoutedEvent="Button.Click">
<!-- Insert cool code here-->
</EventTrigger>
</Button.Triggers>
</Button>
</Grid>
</Page>
有没有办法让这个 EventTrigger
将焦点放在文本框“txtName”上?
我正在尝试找到使用严格的 MVVM 来执行此类操作的方法。如果这是不应该通过 XAML(在 MVVM 中)完成的事情,那也没关系。但我希望看到某种文档,说明它如何适合在 XAML 之外执行的 MVVM 模式。
最佳答案
您是否考虑过使用附加行为。它们易于实现和使用 AttachedProperty。虽然它仍然需要代码,但这段代码被抽象到一个类中并被重用。它们可以消除“代码隐藏”的需要,并且经常与 MVVM 模式一起使用。
试试这个,看看它是否适合你。
public class EventFocusAttachment
{
public static Control GetElementToFocus(Button button)
{
return (Control)button.GetValue(ElementToFocusProperty);
}
public static void SetElementToFocus(Button button, Control value)
{
button.SetValue(ElementToFocusProperty, value);
}
public static readonly DependencyProperty ElementToFocusProperty =
DependencyProperty.RegisterAttached("ElementToFocus", typeof(Control),
typeof(EventFocusAttachment), new UIPropertyMetadata(null, ElementToFocusPropertyChanged));
public static void ElementToFocusPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var button = sender as Button;
if (button != null)
{
button.Click += (s, args) =>
{
Control control = GetElementToFocus(button);
if (control != null)
{
control.Focus();
}
};
}
}
}
然后在您的 XAML 中执行类似...
<Button
Content="Click Me!"
local:EventFocusAttachment.ElementToFocus="{Binding ElementName=textBox}"
/>
<TextBox x:Name="textBox" />
关于c# - WPF - 单击按钮时设置焦点 - 无代码隐藏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2204063/