gpt4 book ai didi

c# - 从Button更新文本框,单击C#

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

我有以下文本框

<TextBox Grid.Column="1" 
Grid.Row="1"
Name="groupAddressBox"
Width ="80"
Text="{Binding Path=GroupAddress, Converter={StaticResource groupAddressConverter}}"/>

当我手动更改文本时,一切都很好。

但是当我尝试通过按钮执行此操作时
private void Test_Click(object sender, RoutedEventArgs e)
{
groupAddressBox.Text = "0/0/1";
}

尽管文本更改了,但是源没有更新,当我单击“确定”时,它会识别出更改之前存在的值。
我无法立即升级源代码,因此我更喜欢这样做。

有什么可以帮助我通过这种方式强制进行源升级的东西吗?

最佳答案

根据您的问题,我尝试创建具有基本功能的MVVM模式的简单示例。请仅对突出显示的代码进行XAML和CS文件的必要更改。

帮助器类

public abstract class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;

protected virtual void OnPropertyChanged(string propName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
}



public class CommandHandler : ICommand
{
public event EventHandler CanExecuteChanged { add { } remove { } }

private Action<object> action;
private bool canExecute;

public CommandHandler(Action<object> action, bool canExecute)
{
this.action = action;
this.canExecute = canExecute;
}

public bool CanExecute(object parameter)
{
return canExecute;
}

public void Execute(object parameter)
{
action(parameter);
}
}

ViewModel
public class ViewModel : ViewModelBase
{
private string groupAddress;
public string GroupAddress
{
get
{
return groupAddress;
}

set
{
if(value != groupAddress)
{
groupAddress = value;
OnPropertyChanged("GroupAddress");

}
}
}

public ViewModel()
{

}

private ICommand clickCommand;
public ICommand ClickCommand
{
get
{
return clickCommand ?? (clickCommand = new CommandHandler(() => MyAction(), true));
}
}

public void MyAction()
{
GroupAddress = "New Group Address";
}
}

窗口Xaml
<TextBox Grid.Column="1" Grid.Row="1" Width ="80" 
Text="{Binding GroupAddress, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>

<Button Content="Push" Style="{StaticResource TransparentButtonStyle}"
Margin="5" Command="{Binding ClickCommand}"/>

Window Xaml CS
ViewModel vm = new ViewModel();

this.DataContext = vm;

关于c# - 从Button更新文本框,单击C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49393270/

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