xamarin 在XAML中设置视图的公共属性

1tu0hz3e  于 5个月前  发布在  其他
关注(0)|答案(1)|浏览(48)

我经常喜欢将XAML文件分解为更小的部分,而不使控件完全独立于视图。

<VerticalStackLayout>
   <Grid>
       <Label Text="item1" />
       ...
   </Grid>

   <Grid>
       <Label Text="item2" />
       ...
   </Grid>
</VerticalStackLayout>

字符串
我通常有(我的页面)

<VerticalStackLayout>
   <myconrols:MyItemView />
   <myconrols:MyItemView />
</VerticalStackLayout>


和一个单独的MyItemView

<Grid>
    <Label Text="item1" x:Name="NameLabel" x:FieldModifier="Public" />
    ...


现在的问题是:有没有可能直接从页面XAML文件中设置NameLabel.Text值?而不定义样板可绑定的属性?

<mycontrols:MyItemView NameLabel.Text="item1" />
<mycontrols:MyItemView NameLabel.Text="item2" />


如果这是不可能的,那么你会如何命名这个功能?(我想创建一个功能问题,因为我认为这将是超级有用的)

lrpiutwd

lrpiutwd1#

有没有可能直接从页面XAML文件中设置NameLabel.Text值?而不需要定义可绑定的属性?
如果你经常重用一个布局,定制一个Contenview是一个很好的方法。由于我们不能通过x:Name属性直接引用Contenview中的控件,所以我们需要添加必要的BindableProperty
这里是一个定制的Contenview,你可以参考它的代码。

MyItemView.xaml.cs

public partial class MyItemView : ContentView
{
      public MyItemView()
      {
            InitializeComponent();
      }

    public String YourName
    {
        get
        {
            String value = (String)GetValue(YourNameProperty);
            return value;
        }
        set
        {
            SetValue(YourNameProperty, value);
        }
    }

    public static readonly BindableProperty YourNameProperty = BindableProperty.Create(nameof(YourName)
    , typeof(String)
    , typeof(MyItemView), defaultBindingMode: BindingMode.TwoWay, propertyChanged: OnYourNameChanged);

    static void OnYourNameChanged(BindableObject bindable, object oldValue, object newValue)
    {
        Console.WriteLine("-----------------> " + newValue);
    }
}

字符串

MyItemView.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentView xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MauiApp1124.Views.MyItemView"
               x:Name="myItemView"
             >
    <VerticalStackLayout>
        <Grid>
            <Label  Text="{Binding Source={x:Reference myItemView}, Path=YourName}" />
        </Grid>
    </VerticalStackLayout>
</ContentView>


下面是使用示例:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:views="clr-namespace:MauiApp1124.Views"
             x:Class="MauiApp1124.MainPage">

        <VerticalStackLayout
            Spacing="25"
            Padding="30,0"
            VerticalOptions="Center">
        <views:MyItemView YourName="welcome"></views:MyItemView>

        <views:MyItemView YourName="Hi"></views:MyItemView>

        </VerticalStackLayout>
</ContentPage>


欲了解更多信息,请查看官方文档:ContentView

相关问题