这是我的Button声明,用.xaml文件编写:
<dxlc:LayoutGroup Orientation="Horizontal" Margin="5,15,0,5">
<Grid MinWidth="100">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Button
IsEnabled="{Binding IsSearchCriteriaHasValue}"
Content="Search"
MaxHeight="25"
MaxWidth="70"
ClipToBounds="True"
VerticalAlignment="Center"
HorizontalAlignment="Center"
HorizontalContentAlignment="Center"
VerticalContentAlignment="Center"
Command="{Binding SearchCommand}"/>
</Grid>
</dxlc:LayoutGroup>
无论用户是否在搜索按钮旁边的搜索框中键入了任何搜索文本,这都是返回true / false的函数 . 该函数位于另一个.cs文件中:
public bool isButtonEnabled
{
return (SearchBox.Selection.Count > 0);
}
问题是isEnabled的值永远不会改变,它保持为真,即按钮始终保持启用状态,或者如果我更改>符号,则按钮始终处于禁用状态 . 有什么建议?
5 回答
IsSearchCriteriaHasValue
需要引发一个更改的事件,您可以使用INotifyPropertyChanged
接口执行此操作:您可以为按钮编写触发器(SearchBox看起来像UI控件)
<Setter Property =“IsEnabled”Value =“True”/>
<Style.Triggers>
<DataTrigger Binding =“{Binding Selection.Count,ElementName = SearchBox}”Value =“0”>! - 您也可以使用convertor
<Setter Property =“IsEnabled”Value =“False”/>
</ DataTrigger>
</Style.Triggers>
</ Style> </Button.Style> </ Button>
它与XAML没有问题,它的通知问题 . 我希望你知道INotifyProperty接口的NotifyPropertyChanged事件 . 只有在ViewModel中为属性触发了该属性,UI才会获取通知并对其进行更新 .
如果SearchBox.Selection计数发生更改,它不会触发任何IsSearchCriteriaHasValue属性的通知,表明它已被更改并且UI应该更新 .
让我们说SearchBox.Selection绑定到observableCollection并且集合发生变化,然后订阅observableCollection以进行添加/删除然后触发
NotifyPropertyChanged("IsSearchCriteriaHasValue")
;那里 .绑定适用于属性更改事件 . 您的
ViewModel
应该实现INotifyPropertyChanged
接口 .https://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged(v=vs.110).aspx
一个例子:
}
绑定适用于属性更改事件 . 您的ViewModel应该实现
INotifyPropertyChanged
接口 . 而且你需要在属性集中提升属性更改事件 . 或者只需在CanExecute方法中使用delegate command
并写入启用禁用逻辑 . 请参阅此链接了解更多信息http://www.codeproject.com/Questions/179129/MVVM-Enable-Disable-button-via-a-PropertyChanged-e