强制或以其他方式启动TwoWay TestBox数据绑定

时间:2014-09-07 20:27:52

标签: c# wpf xaml mvvm data-binding

我有一个WPF TextBoxTwoWay绑定到ViewModel属性。我还有ToolBar Button。单击按钮时,它会在同一command上执行ViewModel,该TextBox会对Binding绑定的属性执行某些操作。

不幸的是,当TextBox失去焦点时,Button似乎只将文本发送回绑定目标。但是,工具栏上的Command在点击时不会获得焦点。结果是<DockPanel LastChildFill="True" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" > <ToolBarTray Background="White" DockPanel.Dock="Top"> <ToolBar Band="1" BandIndex="1"> <Button Command="{Binding QueryCommand}"> <Image Source="images\media_play_green.png" /> </Button> </ToolBar> </ToolBarTray> <DataGrid VerticalAlignment="Top" DockPanel.Dock="Top" Height="450" AutoGenerateColumns="True" ItemsSource="{Binding}" DataContext="{Binding Results}" DataContextChanged="DataGrid_DataContextChanged"/> <TextBox DockPanel.Dock="Bottom" Text="{Binding Sql, Mode=TwoWay}" AcceptsReturn="True" AcceptsTab="True" AutoWordSelection="True" TextWrapping="WrapWithOverflow"/> </DockPanel> 执行它时没有文本框中的文本,而是绑定的最后一个值。

Xaml看起来像这样:

TextBox's

如何在按下ViewModel ToolBar时获取button文字绑定以更新public class MainViewModel : ViewModelBase { private readonly IMusicDatabase _database; /// <summary> /// Initializes a new instance of the MainViewModel class. /// </summary> public MainViewModel(IMusicDatabase database) { _database = database; QueryCommand = new RelayCommand(Query); } public RelayCommand QueryCommand { get; private set; } private async Task QueryAndSetResults() { Results = await _database.Query(Sql); } private void Query() { QueryAndSetResults(); } private IEnumerable<object> _results; public IEnumerable<object> Results { get { return _results; } private set { Set<IEnumerable<object>>("Results", ref _results, value); } } private string _sql = "SELECT * FROM this WHERE JoinedComposers = 'Traditional'"; public string Sql { get { return _sql; } set { Set<string>("Sql", ref _sql, value); } } } 。 ViewModel中没有任何花哨的东西如下:

{{1}}

1 个答案:

答案 0 :(得分:1)

您可以使用绑定的UpdateSourceTrigger属性,将其设置为PropertyChanged使TextBox每次文本更改时刷新绑定,而不仅仅是在失去焦点时:

<TextBox DockPanel.Dock="Bottom"
    Text="{Binding Sql, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" 
    AcceptsReturn="True" 
    AcceptsTab="True" 
    AutoWordSelection="True" 
    TextWrapping="WrapWithOverflow"/>

MSDN的更多信息。