求助:如何将.NET Maui中DXExpress日历月份绑定到按钮文本
实现.NET Maui中按钮与弹窗内DXExpress日历的月份同步
1. 准备ViewModel(核心绑定逻辑)
创建实现INotifyPropertyChanged的ViewModel,托管同步用的日期属性:
using System.ComponentModel; using System.Runtime.CompilerServices; using System.Windows.Input; public class CalendarViewModel : INotifyPropertyChanged { private DateTime _selectedDate = DateTime.Now; public DateTime SelectedDate { get => _selectedDate; set { if (_selectedDate != value) { _selectedDate = value; OnPropertyChanged(); // 同步日历显示的月份 DisplayDate = new DateTime(value.Year, value.Month, 1); } } } private DateTime _displayDate = DateTime.Now; public DateTime DisplayDate { get => _displayDate; set { if (_displayDate != value) { _displayDate = value; OnPropertyChanged(); // 切换月份时同步选中日期到当月第一天 SelectedDate = new DateTime(value.Year, value.Month, 1); } } } public ICommand OpenCalendarPopupCommand { get; } public CalendarViewModel() { OpenCalendarPopupCommand = new Command(async () => { var popup = new CalendarPopup(); popup.BindingContext = this; await Application.Current.MainPage.ShowPopupAsync(popup); }); } public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } }
2. 主页面XAML(绑定按钮文本)
设置页面绑定上下文,将按钮文本绑定到格式化后的月份:
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:YourNamespace" x:Class="YourNamespace.MainPage"> <ContentPage.BindingContext> <local:CalendarViewModel /> </ContentPage.BindingContext> <VerticalStackLayout> <Button Text="{Binding SelectedDate, StringFormat='{0:MMMM yyyy}'}" Command="{Binding OpenCalendarPopupCommand}" /> </VerticalStackLayout> </ContentPage>
3. 弹窗XAML(绑定DXExpress日历)
创建弹窗页面,将DxCalendar的关键属性双向绑定到ViewModel:
<ContentView xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:dxc="clr-namespace:DevExpress.Maui.Editors;assembly=DevExpress.Maui.Editors" x:Class="YourNamespace.CalendarPopup"> <VerticalStackLayout> <dxc:DxCalendar SelectedDate="{Binding SelectedDate, Mode=TwoWay}" DisplayDate="{Binding DisplayDate, Mode=TwoWay}" SelectionMode="Single" /> <Button Text="确定" Clicked="OnConfirmClicked" /> </VerticalStackLayout> </ContentView>
4. 弹窗后台代码(关闭逻辑)
处理弹窗确定按钮的关闭操作:
private void OnConfirmClicked(object sender, EventArgs e) { ((Popup)Parent).Close(); }
关键逻辑说明
- 通过双向绑定让日历的
DisplayDate(显示月份)和SelectedDate与ViewModel同步,按钮文本通过StringFormat直接渲染月份名称。 - 用户切换日历月份时,
DisplayDate的变更会触发ViewModel属性更新,进而同步SelectedDate,最终自动刷新按钮文本。 - 弹窗绑定上下文直接复用主页面ViewModel实例,避免因对象不一致导致绑定失效。
内容的提问来源于stack exchange,提问作者Fernando
相关产品推荐
相关产品推荐

