gpt4 book ai didi

wpf - 动态改变 FocusManager.FocusedElement

转载 作者:行者123 更新时间:2023-12-02 01:12:49 25 4
gpt4 key购买 nike

我有如下的 WPF xaml 代码:

  <StackPanel  FocusManager.FocusedElement="{Binding FocusedElement}">
<TextBox Name="txtbox1" Text="FirstText"/>
<TextBox Name="txtbox3" Text="SecondText"/>
<TextBox Name="txtbox2" Text="ThirdText"/>
</StackPanel>

如何将 FocusedElement 绑定(bind)到 ViewModel 中的属性? 类似的代码如下:

Switch(Type)
{
Case "FirstType" :
FocusedElement = "txtbox1";
break;
Case "SecondType" :
FocusedElement = "txtbox2";
break;
Case "ThiredType" :
FocusedElement = "txtbox3";
break;
}

最佳答案

viewmodel 永远不应该知道 View ,当然也不知道一些 UIElement 名称。但是鉴于 View 模型确实需要能够管理焦点(我建议您在继续之前确保确实如此),您可以这样做:

enter image description here

View 模型:

public enum Focuses
{
None = 0,
First,
Second,
Third
}

public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}

private Focuses _focusedElement;
public Focuses FocusedElement { get { return _focusedElement; } set { _focusedElement = value; OnPropertyChanged("FocusedElement"); } }


public ViewModel()
{
this.FocusedElement = Focuses.Second;
}
}

Xaml:

<StackPanel >
<TextBox Name="txtbox1" Text="FirstText"/>
<TextBox Name="txtbox2" Text="SecondText"/>
<TextBox Name="txtbox3" Text="ThirdText"/>
<StackPanel.Style>
<!-- cannot use DataTriggers directly in StackPanel.Triggers, therefore Style -->
<Style TargetType="{x:Type StackPanel}">
<Style.Triggers>
<DataTrigger Binding="{Binding FocusedElement}" Value="First">
<Setter Property="FocusManager.FocusedElement" Value="{Binding ElementName=txtbox1}"/>
</DataTrigger>
<DataTrigger Binding="{Binding FocusedElement}" Value="Second">
<Setter Property="FocusManager.FocusedElement" Value="{Binding ElementName=txtbox2}"/>
</DataTrigger>
<DataTrigger Binding="{Binding FocusedElement}" Value="Third">
<Setter Property="FocusManager.FocusedElement" Value="{Binding ElementName=txtbox3}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</StackPanel.Style>
</StackPanel>

关于wpf - 动态改变 FocusManager.FocusedElement,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15321047/

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