您可以简单地在父控件上覆盖 OnPropertyChanged 来更新内部控件:
protected override void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
base.OnPropertyChanged(propertyName);
if(propertyName == nameof(IsEnabled))
{
//update controls here
...
}
}
但我宁愿建议您在将内部控件的Opacity 绑定到父级的IsEnabled 属性时使用转换器。
例如,如果您在 C# 中定义了自定义控件,则可以将绑定定义为:
public class ImageButton : Grid
{
private static readonly BooleanToOpacityConverter _converter = new BooleanToOpacityConverter();
public ImageButton()
{
var label = new Label { Text = "ImageButton" };
var image = new Image { Source = ImageSource.FromFile("icon.png") };
// add binding to Opacity using IsEnabled from parent
label.SetBinding(OpacityProperty, new Binding("IsEnabled", converter: _converter, source: this));
image.SetBinding(OpacityProperty, new Binding("IsEnabled", converter: _converter, source: this));
ColumnDefinitions = new ColumnDefinitionCollection { new ColumnDefinition(), new ColumnDefinition() };
SetColumn(label, 1);
Children.Add(label);
Children.Add(image);
}
}
或者,如果您使用基于 XAML 的自定义控件,您可以将绑定分配为:
<Grid xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:UpdateSourceTriggerApp"
x:Name="_parent"
x:Class="UpdateSourceTriggerApp.ImageButton2">
<Grid.Resources>
<ResourceDictionary>
<local:BooleanToOpacityConverter x:Key="_converter" />
</ResourceDictionary>
</Grid.Resources>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Image Source="icon.png" Opacity="{Binding Source={x:Reference _parent}, Path=IsEnabled, Converter={StaticResource _converter}}" />
<Label Text="ImageButton2" Grid.Column="1" Opacity="{Binding Source={x:Reference _parent}, Path=IsEnabled, Converter={StaticResource _converter}}" />
</Grid>
一个示例转换器如下所示:
public class BooleanToOpacityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var isEnabled = (value == null) ? false : (bool)value;
return isEnabled ? 1 : 0.5;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}