Search code examples
c#wpfxamlwindows-phone-8mvvm

Binding a specific database field to a textbox directly in xaml/wpf


I try to bind a specific database field to a textbox. I'm working on a windows phone 8 application with the mvvm pattern.

The C# code works like this:

Binding binding = new Binding();
binding.Source = App.ViewModel.AllSettingsItems.First(x => x.ItemName == "Sample").Value;
this.txtSample.SetBinding(TextBox.TextProperty, binding);

The table has 4 columns: id(int), itemName(String), isActivated(bool), value(String)

Is there a way to do this directly in xaml?

Thanks in advance!


Solution

  • Try this:

    XAML:

    <ListBox x:Name="LstDB">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding id}" Margin="10,0,0,0"></TextBlock>
                    <TextBlock Text="{Binding itemName}" Margin="20,0,0,0"></TextBlock>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
    

    CS:

    public MainPage()
    {
        InitializeComponent();
        loadData();
    }
    
    public void loadData()
    {
        List<DB> list = new List<DB>();
        list.Add(new DB(1, "Item1", true, "10"));
        list.Add(new DB(2, "Item2", false, "20"));
        list.Add(new DB(3, "Item3", true, "30"));
        list.Add(new DB(4, "Item4", false, "40"));
        list.Add(new DB(5, "Item5", true, "50"));
        LstDB.ItemsSource = list;
    }
    
    public class DB
    {
        public int id { get; set; }
        public string itemName { get; set; }
        public bool isActivated { get; set; }
        public string value { get; set; }
    
        public DB()
        { }
    
        public DB(int id, string itemName, bool isActivated, string value)
        {
            this.id = id;
            this.itemName = itemName;
            this.isActivated = isActivated;
            this.value = value;
        }
    }
    

    here, you just need to fetch data from Database and fill it list or any collection and provide itemsource to listbox or any control that you are binding.