遵循 MVVM 模式。每次 TextBox 中的 Text 更改时,我都需要 TextBox 来触发 viewModel 上的属性设置器。问题是 ViewModel 上的 setter 永远不会被调用。这就是我所拥有的:
查看 (.cs)
public partial class AddShowView : PhoneApplicationPage
{
public AddShowView()
{
InitializeComponent();
}
private void PhoneApplicationPage_Loaded_1(object sender, RoutedEventArgs e)
{
DataContext = new AddShowViewModel(this.NavigationService);
}
private void SearchTextBox_TextChanged_1(object sender, TextChangedEventArgs e)
{
var textBox = (TextBox)sender;
var binding = textBox.GetBindingExpression(TextBox.TextProperty);
binding.UpdateSource();
}
}
查看 (.xaml),仅相关部分
<TextBox Grid.Row="0" HorizontalAlignment="Stretch" VerticalAlignment="Center" Text="{Binding SearchText, UpdateSourceTrigger=Explicit}" TextChanged="SearchTextBox_TextChanged_1" />
视图模型
public class AddShowViewModel : PageViewModel
{
#region Commands
public RelayCommand SearchCommand { get; private set; }
#endregion
#region Public Properties
private string searchText = string.Empty;
public string SearchText
{
get { return searchText; }
set
{
searchText = value;
SearchCommand.RaiseCanExecuteChanged();
}
}
#endregion
public AddShowViewModel(NavigationService navigation) : base(navigation)
{
SearchCommand = new RelayCommand(() => MessageBox.Show("Clicked!"), () => !string.IsNullOrEmpty(SearchText));
}
}
从源到目标的绑定有效,我已经仔细检查过,所以 DataContext 设置正确。我不知道我哪里出错了。感谢您的帮助。