通过视图模型和绑定访问文本框
本文关键字:访问 文本 绑定 视图 模型 | 更新日期: 2023-09-27 17:54:20
我创建了一个c# WPF程序,其中我有一个TextBox
。我想让这个TextBox
用viewmodel
给出事件的反馈。
简化示例:单击按钮后,TextBox
显示"...Button clicked"
。
我现在把它放在后面的代码中:
public partial class MainWindow : Window
{
//.....
public void FeedbackPanel(string text)
{
if (FeedbkPanelTextBox != null)
{
if (text != null)
{
FeedbkPanelTextBox.AppendText(text + "'n");
}
else
{
FeedbkPanelTextBox.AppendText("Null'n");
}
}
else
{
return;
}
}
}
如何将这些代码移动到viewmodel
并在view
中使用绑定?
编辑
快速示例:
<Window x:Class="ButtonClickedFeedbackICommand.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ButtonClickedFeedbackICommand"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.DataContext>
<local:ViewModel/>
</Grid.DataContext>
<StackPanel Orientation="Horizontal">
<TextBox x:Name="tbFeedback"
Text="{Binding ClickedFeedback}"
MinWidth="50"
Background="SlateGray"
VerticalAlignment="Center"/>
<Button Content="Click"
Command="{Binding TestCommand}"
CommandParameter="{Binding ElementName=tbFeedback, Path=Text}"
VerticalAlignment="Center" />
</StackPanel>
</Grid>
这是你的视图。为了支持你所说的,我们需要一种与其他类交流的方法。我们的按钮将使用一个命令和一个CommandParameter,这将利用访问文本框的文本属性。
这是你的简单ViewModel:
public class ViewModel
{
public ICommand TestCommand { get; set; }
public ViewModel()
{
TestCommand = new TestCommand(this);
}
public void FeedbackPanel(string text)
{
if (text != null)
{
if (text != null)
{
text += (text + "'n");
}
else
{
text += ("Null'n");
}
}
else
{
return;
}
}
}
}
和命令:
public class TestCommand : ICommand
{
public ViewModel _vm { get; set; }
public TestCommand(ViewModel vm)
{
_vm = vm;
}
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
_vm.FeedbackPanel(parameter.ToString());
}
}
你可以选择在那个CommandParameter中发送另一个东西。我认为心流尊重你的需求。随便玩一会儿吧。