我建议使用转换器。这是示例。假设你有一个简单的 ViewModel 类:
class ViewModel
{
public string Read
{ get; set; }
public string ReadWrite
{ get; set; }
public bool IsPropertyReadOnly(string propertyName)
{
return propertyName != "ReadWrite";
}
}
要解决您的问题,您需要编写一个转换器,例如:
public class Converter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var vm = value as ViewModel;
var functionName = (string)parameter;
var result = vm.IsPropertyReadOnly(functionName);
return result;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException("This method should never be called");
}
}
就这样; 现在您可以在 XAML 中使用此转换器,例如:
<Window.Resources>
<temp:Converter x:Key="ReadOnlyMethodConverter"/>
</Window.Resources>
<StackPanel>
<TextBox Text="{Binding Read, Mode=TwoWay}"
IsReadOnly="{Binding Path=.,
Converter={StaticResource ReadOnlyMethodConverter}, ConverterParameter=Read}"
/>
<TextBox Text="{Binding ReadWrite, Mode=TwoWay}"
IsReadOnly="{Binding Path=.,
Converter={StaticResource ReadOnlyMethodConverter}, ConverterParameter=ReadWrite}"
/>
</StackPanel>
在代码隐藏中,我们只需创建 ViewModel 并将其设置为 DataContext:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModel();
}
}