XAML数据绑定

介绍XAML数据绑定的技巧

  1. 绑定自身属性
    {Binding Source={RelativeSource Self}, Path=WidthRequest}

    1
    
    <ImageButton Aspect="Fill" HeightRequest="60" WidthRequest="{Binding Source={RelativeSource Self}, Path=HeightRequest}" />
    

    CommandParameter绑定控件对象本身,使用CommandParameter="{Binding Source={RelativeSource Self}}"。

    1
    
    <TapGestureRecognizer Command="{Binding GoHomeCommand}" CommandParameter="{Binding Source={RelativeSource Self}}"/>
    

    CommandParameter绑定其他控件对象,使用CommandParameter="{x:Reference entry}"。

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    
    <ContentPage.Behaviors>
            <toolkit:EventToCommandBehavior
            EventName="NavigatedTo"
            x:TypeArguments="Entry"
            CommandParameter="{x:Reference entry}"
            Command="{Binding NavigatedToCommand}" />
            <toolkit:EventToCommandBehavior
            EventName="NavigatedFrom"
                x:TypeArguments="Entry"
    CommandParameter="{x:Reference entry}"
            Command="{Binding NavigatedFromCommand}" />
        </ContentPage.Behaviors>
    
        <Entry x:Name="entry"  Keyboard="Numeric"/>
    
  2. 绑定主题变量
    Source="{Binding Source={StaticResource monkey}, Converter={StaticResource ImageResourceConverter}}"

    1
    2
    3
    4
    5
    6
    7
    8
    
    <ImageButton Aspect="Fill" HeightRequest="60" WidthRequest="{Binding Source={RelativeSource Self}, Path=HeightRequest}" Source="{Binding Source={StaticResource monkey}, Converter={StaticResource ImageResourceConverter}}"/>
    
    <ResourceDictionary xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 x:Class="RuiChao.Library.Resources.Themes.LightTheme">
        <x:String x:Key="monkey">monkey.png</x:String>
        <Color x:Key="PageBackgroundColor">green</Color>
    </ResourceDictionary>
    
  3. 绑定到源
    句点 (.) Text="{Binding}" 等效于 Text="{Binding Path=.}" 
    XAML 代码

    1
    
    <Image Source="{Binding Path=., Source={StaticResource Logo}, Converter={StaticResource ImageResourceConverter}}" HeightRequest="50" Aspect="AspectFit" />
    

    C#代码

    1
    
    image.SetBinding(Image.SourceProperty, new Binding(".", source:Application.Current.Resources["ChongQing"], converter: new CustomImageResourceConverter()));
    
  4. 参考文件
    https://learn.microsoft.com/zh-cn/dotnet/desktop/wpf/data/binding-declarations-overview?view=netdesktop-7.0

  5. 数据模板(DataTemplate)中事件绑定
    使用CollectionView替代ListView,ListView中的数据模板绑定内容无法同步。
    模板中的控件默认绑定到模板父级,如果需要绑定到ViewModel中的方法,需要在页面(ContentPage)先定义x:Name,然后在Command中进行绑定。

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    
    <basePage:BasePage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"             
                 x:Class="RuiChao.Measurement.ForcedSpirometry.Pages.ForcedSpirometryReviewPage"          
                 xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"
                 x:TypeArguments="vm:ForcedSpirometryReviewViewModel"
                 x:DataType="vm:ForcedSpirometryReviewViewModel"
                 x:Name="forcedSpirometryReviewPage"
                 Shell.PresentationMode="NotAnimated"
                 Shell.NavBarIsVisible="false" 
                 BackgroundColor="{DynamicResource PageBackgroundColor}"
                 Title="ForcedSpirometryReviewPage">
    
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    
    <Grid Grid.Column="2">                
                    <Border Stroke="gray" Margin="10, 10">
                        <CollectionView ItemsSource="{Binding ReviewTrialInfos}" x:Name="Listview">
                            <CollectionView.ItemTemplate>
                                <DataTemplate x:DataType="models:ReviewTrialInfo">
                                    <Grid Padding="10">
                                        <Grid.ColumnDefinitions>
                                            <ColumnDefinition Width="*" />
                                            <ColumnDefinition Width="*" />
                                            <ColumnDefinition Width="*" />
                                        </Grid.ColumnDefinitions>
                                        <Label Text="{Binding Number}" />
                                        <Grid Grid.Column="1" RadioButtonGroup.GroupName="ex">
                                            <RadioButton IsChecked="{Binding IsBestEx}" >
                                                <RadioButton.Behaviors>
                                                    <!--<toolkit:EventToCommandBehavior                                                       
                                                        EventName="CheckedChanged"
                                                        Command="{Binding Path=BindingContext.AAACommand,
                                                                    Source={RelativeSource AncestorType={x:Type vm:ForcedSpirometryReviewViewModel}}}"
                                                        CommandParameter="{Binding}"
                                                       />-->
                                                    <!--<toolkit:EventToCommandBehavior
                                                        x:DataType="vm:ForcedSpirometryReviewViewModel"
                                                        EventName="CheckedChanged"
                                                        Command="{Binding Path=AAACommand,
                                                                    Source={RelativeSource Mode=FindAncestorBindingContext, AncestorType={x:Type vm:ForcedSpirometryReviewViewModel}}}"
                                                        CommandParameter="{Binding}"/>-->
                                                    <toolkit:EventToCommandBehavior
    
                                                        EventName="CheckedChanged"
                                                        Command="{Binding Path=BindingContext.AAACommand,
                                                                    Source={Reference forcedSpirometryReviewPage}}"
                                                        CommandParameter="{Binding}"/>
                                                    <!--<toolkit:EventToCommandBehavior
    
                                                        EventName="Focused"
                                                        Command="{Binding AAACommand}"
                                                        CommandParameter="{Binding .}"/>-->
                                                </RadioButton.Behaviors>
                                            </RadioButton>
                                        </Grid>
                                        <Grid Grid.Column="2" RadioButtonGroup.GroupName="in">
                                            <RadioButton IsChecked="{Binding IsBestIn}" CheckedChanged="RadioButton_CheckedChanged" />
                                        </Grid>
                                    </Grid>
                                </DataTemplate>
                            </CollectionView.ItemTemplate>
                        </CollectionView>
                    </Border>
                </Grid>
    
  6. 绑定时传递事件对象
    通过x:TypeArguments参数设置事件类,例如:在CollectionView中为SelectionChanged事件传递SelectionChangedEventArgs事件的参数设置x:TypeArguments="SelectionChangedEventArgs"

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    
    <CollectionView ItemsSource="{Binding Patients}"
                IsEnabled="{Binding CheckSpirometryCommand.IsRunning, Mode=OneWay, Converter={StaticResource InvertedBoolConverter}}"
                SelectionMode="Single">
        <CollectionView.Behaviors>
            <toolkit:EventToCommandBehavior
                x:TypeArguments="SelectionChangedEventArgs"
                EventName="SelectionChanged"
                Command="{Binding SelectionChangedCommand}" />
        </CollectionView.Behaviors>
        <CollectionView.ItemTemplate>
            <!--<DataTemplate>-->
            <DataTemplate x:DataType="database:Patient">
                <StackLayout Orientation="Horizontal">
                    <!--<Label Text="{Binding Id}" FontSize="24" VerticalOptions="Center" />
                <Label Text="{Binding FirstName}" FontSize="24" VerticalOptions="Center" Margin="30,0"/>-->
                    <Label Text="{Binding Source={RelativeSource AncestorType={x:Type database:Patient}, AncestorLevel=1}, Path=Id}" FontSize="24" VerticalOptions="Center" />
                    <Label Margin="30,0" Text="{Binding FirstName, Source={RelativeSource AncestorType={x:Type database:Patient}}}" FontSize="24" VerticalOptions="Center" />
                </StackLayout>
    
                <!--<Grid Padding="10">
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="Auto" />
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto" />
                    <ColumnDefinition Width="Auto" />
                </Grid.ColumnDefinitions>
                <Image Grid.RowSpan="2" 
           Source="{Binding ImageUrl}" 
           Aspect="AspectFill"
           HeightRequest="60" 
           WidthRequest="60" />
                <Label Grid.Column="1" 
           Text="{Binding Name}" 
           FontAttributes="Bold" />
                <Label Grid.Row="1"
           Grid.Column="1" 
           Text="{Binding Location}"
           FontAttributes="Italic" 
           VerticalOptions="End" />
            </Grid>-->
            </DataTemplate>
        </CollectionView.ItemTemplate>
    </CollectionView>
    
  7. 多重绑定字符串

    1
    2
    3
    4
    5
    6
    
    <MenuFlyoutItem.Text>
        <MultiBinding StringFormat="{}{0}/{1}">
            <Binding Path="LocalizationResourceManager[Start]"/>
            <Binding Path="LocalizationResourceManager[Stop]"/>
        </MultiBinding>
    </MenuFlyoutItem.Text>
    
Built with Hugo
Theme Stack designed by Jimmy