Xamarin中Entry与ViewModel绑定问题及平均值计算实现求助
Hey there! Let's work through fixing your binding issues and getting that average calculation up and running properly. Here are the key problems in your code and step-by-step fixes:
1. 修正XAML中的绑定错误
Your Entry controls have incorrect binding setups that are blocking values from reaching your ViewModel:
- Remove the
BindingContext="{x:Reference Rechner}"from each Entry — the page’s BindingContext is already set to yourCommandDemoViewModel, so Entries inherit this automatically. - Fix the binding path: You don’t need the invalid
CommanDemoViewModelProperty[modal]syntax. Bind directly to the ViewModel propertiesErsteNummer,ZweiteNummer, andDritteNummer. - Add
Mode=TwoWayto the Text binding (to send user input back to the ViewModel) and use yourstringConverterto handle string-to-double conversion.
Updated Entry code in XAML:
<Entry x:Name="Number1" Placeholder="Number1" Keyboard="Numeric" Text="{Binding ErsteNummer, Mode=TwoWay, Converter={StaticResource stringConverter}}" /> <Entry x:Name="Number2" Placeholder="Number2" Keyboard="Numeric" Text="{Binding ZweiteNummer, Mode=TwoWay, Converter={StaticResource stringConverter}}" /> <Entry x:Name="Number3" Placeholder="Number3" Keyboard="Numeric" Text="{Binding DritteNummer, Mode=TwoWay, Converter={StaticResource stringConverter}}" />
2. 修复ViewModel中的错误
There are two critical issues in your CommandDemoViewModel:
- Delete the invalid line:
BindableProperty.Create()— this code is meant for custom controls, not ViewModels, and will cause compilation errors. - Ensure your
DoubleToStringConvertersupports two-way conversion (to handle both displaying values and parsing user input). If you don’t have a complete implementation, use this:
public class DoubleToStringConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return value is double d ? d.ToString() : string.Empty; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { if (double.TryParse(value?.ToString(), out double result)) return result; return 0.0; } }
3. 简化平均值计算逻辑
Your CalculateAv method works fine, but you can make the command execution more readable by using the ViewModel properties directly (though using the backing fields also works if binding is correct):
MultiplyBy2Command = new Command(execute: () => CalculateAv(ErsteNummer, ZweiteNummer, DritteNummer));
4. 清理冗余资源
You have a duplicate CommandDemoViewModel instance in your Resources (<local:CommandDemoViewModel x:Key="model" />) — you don’t need this since the page already has a BindingContext set. Remove it to avoid confusion.
测试验证
After making these changes:
- Enter numbers into the three Entry fields.
- Tap the "Multiply by 2" button (I get it, the text doesn’t match the function, as you noted!) — the
Ausgabelabel will now display the average of your three input numbers.
内容的提问来源于stack exchange,提问作者mx1txm

