遵循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设置正确。我不知道我哪里出错了。 谢谢你的帮忙。
答案 0 :(得分:1)
您需要将绑定模式设置为TwoWay,否则它只会从ViewModel中读取值,而不是更新它。
Text="{Binding SearchText, Mode=TwoWay, UpdateSourceTrigger=Explicit}"