我有一个WPF TextBox
,TwoWay
绑定到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}}
答案 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的更多信息。