gpt4 book ai didi

wpf - WPF专注于带有控件模板的ListBox项

转载 作者:行者123 更新时间:2023-12-03 10:21:10 24 4
gpt4 key购买 nike

我有一个带有将项目模板作为文本框和按钮(添加)的列表框。每当单击按钮时,都会添加一个项目(文本框)。单击按钮后,我想将焦点移到第一个文本框或最近添加的文本框。我如何在WPF中做到这一点。

最佳答案

我完全同意Daniel的回答,但是让我用一些代码来澄清这个想法。

首先,让我们定义对“true”值有 react 的附加行为,并为其所有者设置焦点。

public static class FocusBehaviour
{
public static bool GetForceFocus(DependencyObject d)
{
return (bool)d.GetValue(FocusBehaviour.ForceFocusProperty);
}

public static void SetForceFocus(DependencyObject d, bool val)
{
d.SetValue(FocusBehaviour.ForceFocusProperty, val);
}

public static readonly DependencyProperty ForceFocusProperty =
DependencyProperty.RegisterAttached("ForceFocus",
typeof(bool),
typeof(FocusBehaviour),
new FrameworkPropertyMetadata(false,
FrameworkPropertyMetadataOptions.None,
(d, e) =>
{
if((bool)e.NewValue)
{
if (d is UIElement)
{
((UIElement)d).Focus();
}
}
}));
}

然后将此行为添加到我们的TextBox中:
<DataTemplate>
<TextBox self:FocusBehaviour.ForceFocus="{Binding IsFocused}"/>
</DataTemplate>

当然,您应该将IsFocused属性添加到您的项目类中:
public class Item : ObservableObject
{
//...
private bool _isFocused = true;
public bool IsFocused
{
get
{
return this._isFocused;
}
set
{
this._isFocused = value;
this.OnPropertyChanged("IsFocused");
}
}
}

在代码中的某个位置,您应该使用IsFocused属性来处理商品。
例如,当您添加新项目时,应为所有项目(“新手”除外)重置“IsFocused”。初始化集合时,应仅对第一项设置IsFocused。

关于wpf - WPF专注于带有控件模板的ListBox项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5576753/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com