我在我的XAML中尋找正確的語法來設置ViewModel中的屬性(例如「BusyEditing」),該屬性然後已經鏈接到「IsEnabled」按鈕。 基本上,我希望在我進入一個字段開始編輯它時立即啓用「保存」按鈕。更酷的是,如果該屬性更新了文本框值的更改,而不僅僅是GotFocus。當控件獲取焦點時更新ViewModel中的屬性
在此先感謝。
我在我的XAML中尋找正確的語法來設置ViewModel中的屬性(例如「BusyEditing」),該屬性然後已經鏈接到「IsEnabled」按鈕。 基本上,我希望在我進入一個字段開始編輯它時立即啓用「保存」按鈕。更酷的是,如果該屬性更新了文本框值的更改,而不僅僅是GotFocus。當控件獲取焦點時更新ViewModel中的屬性
在此先感謝。
最簡單的方法是在代碼隱藏方面,雖然這對WPF開發人員來說有點誇張,但它是視圖邏輯,不會破壞單元測試的可能性。
<TextBox GotFocus="GotFocus"/>
<Button Name="SaveButton" Command="{Binding SaveCommand}" IsEnabled="False">
<TextBlock Text="Save"/>
</Button>
然後
private void GotFocus(object sender, RoutedEventArgs e)
{
SaveButton.IsEnabled = true;
}
或者你可以附加一個命令到GotFocus事件(http://stackoverflow.com/questions/1048517/wpf-calling-commands-via-events)設置在「SaveCommand」CanExecute方法中查詢的viewmodel上的布爾值。
聽起來好像你想命名你的屬性IsDirty,只有在模型變髒的時候才能使用Save按鈕。你可能對您的視圖模型CanSave財產覈對時,模型加載,如原始值的新模式值:
public bool CanSave
{
get
{
return this.IsDirty;
}
}
public bool IsDirty
{
get
{
if (this.ModelPropertyValue != this.ModelOriginalPropertyValue)
{
return true;
}
return false;
}
}
private string modelPropertyValue;
public string ModelPropertyValue
{
get
{
return this.modelPropertyValue;
}
set
{
if (this.modelPropertyValue == value)
{
return;
}
this.modelPropertyValue = value;
OnPropertyChanged(() => this.ModelPropertyValue);
OnPropertyChanged(() => this.CanSave);
}
}
文本框默認情況下只在失去重心更新其綁定屬性,所以你會需要設置文本框的UpdateSourceTrigger屬性:
<TextBox Text="{Binding ModelPropertyValue, UpdateSourceTrigger=PropertyChanged}" />
<Button IsEnabled="{Binding CanSave}">Save</Button>
可以使用Commanding很容易做到這一點。如果將ViewModel上的命令綁定到按鈕,並且CanExecute方法從其他輸入中查找有效信息,則該方法將保持禁用狀態,直到滿足該條件。
在MVVM Light它會是這個樣子
public RelayCommand LogonCommand { get; private set; }
LogonCommand = new RelayCommand(
Logon,
CanLogon
);
private Boolean CanLogon(){
return !String.IsNullOrWhiteSpance(SomeProperty);
}
在您的XAML只是一定要按鈕命令綁定到視圖模型命令:
<Button Command="{Binding LogonCommand}" />
如果你的文本框綁定到SomeProperty
這將無需任何額外的工作,沒有必要的代碼。
另外,如果你想擁有這個trigger on property change而不是LostFocus,那麼你需要明確地定義它。
<TextBox>
<TextBox.Text>
<Binding Source="{StaticResource myDataSource}" Path="SomeProperty"
UpdateSourceTrigger="PropertyChanged"/>
</TextBox.Text>
</TextBox>
您將需要使用EventTrigger
。其實,其中兩個。一個用於GotFocus
和其他用於LostFocus
事件。
下面是一個例子:
Using EventTrigger in XAML for MVVM – No Code Behind Code
查找SetProperty
觸發動作。這對你有用。
懶,快速,不那麼優雅的解決方案,如果你只有一個文本框:
<TextBox Name="TB" Width="200"/>
<Button Content="Save">
<Button.Style>
<Style TargetType="Button">
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=TB, Path=Text}" Value="">
<Setter Property="IsEnabled" Value="False"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
該按鈕將盡快有在文本框中的文本啓用。