Data binding controls in C# code (.cs file)

自闭症网瘾萝莉.ら 提交于 2021-01-29 10:22:27

问题


i have been searching for data binding but instead of being in xaml i am searching for being in .cs file, is there a manner (property) that allows me to bind the specific property to a variable?

I want to bind the "Text" property of the "Entry" control but the problem is that how do i do it?

this is what i have tried, but i'm not sure about it beacuse OBVIOUSLY the code wasn't correct

textBox.SetBinding(Entry.TextProperty, 
      "MainViewModel.GetInstance().SubtasksList[TaskNumber - 1]");

code:

var textBox = new Entry()
{
           Placeholder = "ex Math homework",
   TextColor = Xamarin.Forms.Color.FromHex("#18E1BF"),
   HorizontalOptions = LayoutOptions.Center,
   VerticalOptions = LayoutOptions.Center,
   Text = MainViewModel.GetInstance().SubtasksList[TaskNumber - 1]
};

textBox.SetBinding(Entry.TextProperty, 
      "MainViewModel.GetInstance().SubtasksList[TaskNumber - 1]");

when i want to take the data from the property (list index) just it didnt get changed, so why?

In other words, what I want to do is this:

<Entry
               Text="{Binding EntryText}”
               FontAttributes="Bold"
               FontSize="Large"
               HorizontalOptions="Center"
               VerticalOptions="CenterAndExpand" />

But instead of XAML file, use .cs file How I do it?


回答1:


If you are looking to bind an Element (index-based) from a C# Collection to an Entry you can do it this way.

Get your ViewModel instance and set it as the BindingContext on the Page

var viewModel = MainPageViewModel.GetInstace();
BindingContext = viewModel;

Create your entries in case you have more than one:

var textBox1 = new Entry()
{
    Placeholder = "ex Math homework",
    TextColor = Xamarin.Forms.Color.FromHex("#18E1BF"),
    HorizontalOptions = LayoutOptions.Center,
    VerticalOptions = LayoutOptions.Center
};

var textBox2 = new Entry()
{
    Placeholder = "ex Science homework",
    TextColor = Xamarin.Forms.Color.FromHex("#18E1BF"),
    HorizontalOptions = LayoutOptions.Center,
    VerticalOptions = LayoutOptions.Center
};

var textBox3 = new Entry()
{
    Placeholder = "ex English homework",
    TextColor = Xamarin.Forms.Color.FromHex("#18E1BF"),
    HorizontalOptions = LayoutOptions.Center,
    VerticalOptions = LayoutOptions.Center
};

Set your bindings. For this example, since I didn't get what TaskNumber meant I am using fixed indexes instead

textBox1.SetBinding(Entry.TextProperty, "SubtasksList[0]");
textBox2.SetBinding(Entry.TextProperty, "SubtasksList[1]");
textBox3.SetBinding(Entry.TextProperty, "SubtasksList[2]");

Then you just add your Entries to your View. I am using a StackLayout which I called ItemsContainer

ItemsContainer.Children.Add(textBox1);
ItemsContainer.Children.Add(textBox2);
ItemsContainer.Children.Add(textBox3);

The above should give you a result like this:

A Xamarin Page with 3 programmatically created Entries each one bound to an item of a C# Collection.

Hope this helps.-




回答2:


i write a simple sample,you could check it ,if it what you need ,here i add dynamically entries by a ListView:

the page axml:

<ContentPage>
 <ContentPage.Resources>
    <ResourceDictionary>
        <local:GetListConverter x:Key="getList" />
    </ResourceDictionary>
 </ContentPage.Resources>

 <StackLayout Padding="10, 0">
    <Entry x:Name="entry1"
           Text=""
           Placeholder="enter search term"
           VerticalOptions="CenterAndExpand" />
    <ListView ItemsSource="{Binding Source={x:Reference entry1},
                                Path=Text,
                                Converter={StaticResource getList}}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <Entry Text="{Binding .}"></Entry>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
 </StackLayout>
</ContentPage>  

the GetListConverter (get the data list by the entry Text which user input the index):

public class GetListConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (string.IsNullOrEmpty((string)value))
        {
            return null;
        }
        ObservableCollection<string> dataList = MainViewModel.GetInstance().SubtasksList[int.Parse((string)value) - 1];
        return dataList;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }

the effec is like this:



来源:https://stackoverflow.com/questions/58278805/data-binding-controls-in-c-sharp-code-cs-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!