从按钮更新文本框单击C#

时间:2018-03-20 20:09:33

标签: c# wpf mvvm binding

我有以下文本框

<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";
}

尽管文本发生了更改,但源文件未更新,当我单击“确定”时,它会识别更改前的值。 我不能马上升级源代码,所以我更喜欢这样做。

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

1 个答案:

答案 0 :(得分:2)

根据您的问题,我尝试使用非常基本的功能创建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);
        }
    }

<强>视图模型

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"; 
    } 
}

Window 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;