简体   繁体   中英

Is there a way to bind the xaml properties of an element to a new element created by code? (c# xamarin.forms)

XAML File Content

 <StackLayout>
    <!-- Place new controls here -->
    <Label Text="First app in c#" 
       HorizontalOptions="Center"
       VerticalOptions="CenterAndExpand" />
    <ProgressBar x:Name="pbstatus" ProgressColor="LightGreen"  Progress="0.01"/>
</StackLayout>

Actual Code (initializing variables)

    int countvar = 0;
    string buttoncontains = "Click Me";
    ProgressBar progressBar = new ProgressBar { ProgressColor = Color.LightGreen, Progress = 0 };

The Progressbar above the buttons is the one made by the xaml file, the otherone created in the code is not shown or binded to the element, for any reason i cant use the progressbar made in the xaml file.

If you want to add Control by C# to the layout, you can give a name for your StackLayout in xaml.

<StackLayout x:Name="sl">
    <!-- Place new controls here -->
    <Label x:Name="myLabel" Text="First app in c#" 
   HorizontalOptions="Center"
   VerticalOptions="CenterAndExpand" />
    <ProgressBar x:Name="pbstatus" ProgressColor="LightGreen"   Progress="0.01" />
</StackLayout>

Then, add the control(used sl.Children.Add() ) by C# in the backend code,

        string buttoncontains = "Click Me";
        Button button = new Button() {Text= buttoncontains };
        button.Clicked += Button_Clicked;

         ProgressBar progressBar = new ProgressBar { ProgressColor = 
         Color.LightGreen, Progress = 0 };


        sl.Children.Add(button);
        sl.Children.Add(progressBar);

Button click event

 private void Button_Clicked(object sender, EventArgs e)
    {
        pbstatus.Progress = pbstatus.Progress+0.01;
    }

I bind the Button's text(Button created by C#) to the pbstatus's Progress(pbstatus created by xaml),

I used following code.

button.BindingContext = pbstatus;
button.SetBinding(Button.TextProperty, "Progress");

here is running gif.

在此处输入图片说明

Here is a helpful article about binding, you can refer to it.

https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/data-binding/basic-bindings

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM