Skip to content

Commit d299dfd

Browse files
authored
Merge pull request #258 from CommunityToolkit/dev/fix-observableproperty-inherited-canexecute
Fix [ICommand] CanExecute with inherited generated property
2 parents 8256663 + 6af97af commit d299dfd

File tree

2 files changed

+31
-3
lines changed

2 files changed

+31
-3
lines changed

CommunityToolkit.Mvvm.SourceGenerators/Input/ICommandGenerator.Execute.cs

+2-3
Original file line numberDiff line numberDiff line change
@@ -723,11 +723,10 @@ private static bool TryGetCanExecuteMemberFromGeneratedProperty(
723723
ImmutableArray<string> commandTypeArguments,
724724
[NotNullWhen(true)] out CanExecuteExpressionType? canExecuteExpressionType)
725725
{
726-
foreach (ISymbol memberSymbol in containingType.GetMembers())
726+
foreach (ISymbol memberSymbol in containingType.GetAllMembers())
727727
{
728728
// Only look for instance fields of bool type
729-
if (memberSymbol is not IFieldSymbol fieldSymbol ||
730-
fieldSymbol is { IsStatic: true } ||
729+
if (memberSymbol is not IFieldSymbol { IsStatic: false } fieldSymbol ||
731730
!fieldSymbol.Type.HasFullyQualifiedName("bool"))
732731
{
733732
continue;

tests/CommunityToolkit.Mvvm.UnitTests/Test_ObservablePropertyAttribute.cs

+29
Original file line numberDiff line numberDiff line change
@@ -645,6 +645,19 @@ public void Test_ObservableProperty_ModelWithAlsoBroadcastChangeAndDisplayAttrib
645645
CollectionAssert.AreEqual(new[] { nameof(model.SomeProperty) }, propertyNames);
646646
}
647647

648+
// See https://github.com/CommunityToolkit/dotnet/issues/257
649+
[TestMethod]
650+
public void Test_ObservableProperty_InheritedModelWithCommandUsingInheritedObservablePropertyForCanExecute()
651+
{
652+
InheritedModelWithCommandUsingInheritedObservablePropertyForCanExecute model = new();
653+
654+
Assert.IsFalse(model.SaveCommand.CanExecute(null));
655+
656+
model.CanSave = true;
657+
658+
Assert.IsTrue(model.SaveCommand.CanExecute(null));
659+
}
660+
648661
public abstract partial class BaseViewModel : ObservableObject
649662
{
650663
public string? Content { get; set; }
@@ -1037,4 +1050,20 @@ public sealed partial class ModelWithAlsoBroadcastChangeAndDisplayAttributeLast
10371050
[Display(Name = "Foo bar baz")]
10381051
private object? _someProperty;
10391052
}
1053+
1054+
public abstract partial class BaseModelWithObservablePropertyAttribute : ObservableObject
1055+
{
1056+
[ObservableProperty]
1057+
private bool canSave;
1058+
1059+
public abstract void Save();
1060+
}
1061+
1062+
public partial class InheritedModelWithCommandUsingInheritedObservablePropertyForCanExecute : BaseModelWithObservablePropertyAttribute
1063+
{
1064+
[ICommand(CanExecute = nameof(CanSave))]
1065+
public override void Save()
1066+
{
1067+
}
1068+
}
10401069
}

0 commit comments

Comments
 (0)