Binding String property to TextBox Text from Code Behind - c#

Sorry for this basic question
I have a data model :
class data_test
{
public string textdata { get; set; }
public bool booldata { get; set; }
public bool checkdata { get; set; }
public data_opt enumdata { get; set; }
}
Here's Enum :
enum data_opt
{
managed = 1,
unmanaged = 2 ,
mixed = 3
}
Then I create a data model :
var n_Data = new data_test()
{ textdata = "test data",
booldata = false,
checkdata = true ,
enumdata = data_opt.mixed
};
And I create a text box from code behind :
var text_box = new TextBox();
Now I want to bind text_box.Text property to n_Data.textdata from code behind
The same way DataGrid works , two-way connection with real-time update.
I found some pages :
Binding String Property in Code-Behind TextBlock
WPF Data Binding to a string property
Binding string property to object
Unfortunately , none of them worked for me , Here's my code to bind:
Binding binding = new Binding();
binding.Path = new PropertyPath("textdata");
binding.Source = n_Data;
text_box.SetBinding(TextBlock.TextProperty, binding);
Also I tried this :
Binding binding = new Binding();
binding.Path = new PropertyPath("textdata");
binding.Source = n_Data;
BindingOperations.SetBinding(text_box, TextBlock.TextProperty, binding);
Both of them don't work , What am I doing wrong ?

Since your target is a TextBox, you can't use TextBlock.TextProperty as property to bind. You need to use TextBox.TextProperty:
text_box.SetBinding(TextBox.TextProperty, binding);

Related

DataGrid Combobox SelectedValue

I've written a simple example in which a DataGrid on a WPF form is populated entirely from the codebehind. A DataGridTemplateColumn with a ComboBox has the ItemsSource set to a DummyClass that contains two properties for the DisplayMember and the SelectedValue.
A DataTable is populated with a single column with two rows. The ItemsSource for the DataGrid is set to the default view of the DataTable.
When the code runs, each ComboBox in the DataGrid displays correctly and has the proper options available in the dropdown but does not display the values from the DataTable.
What binding am I missing to connect the ComboBox SelectedValue to the values from the DataTable?
public partial class MainWindow : Window
{
public class DummyClass
{
public int SelectedValue { get; set; }
public string DisplayValue { get; set; }
}
public ObservableCollection<DummyClass> DummyClassCollection;
public MainWindow()
{
InitializeComponent();
DummyClassCollection = new ObservableCollection<DummyClass>();
DummyClassCollection.Add(new DummyClass() { DisplayValue = "Item1", SelectedValue = 0 });
DummyClassCollection.Add(new DummyClass() { DisplayValue = "Item2", SelectedValue = 1 });
DummyClassCollection.Add(new DummyClass() { DisplayValue = "Item3", SelectedValue = 2 });
DataGridTemplateColumn templateColumn = new DataGridTemplateColumn();
DataTemplate dataTemplate = new DataTemplate();
FrameworkElementFactory control = new FrameworkElementFactory(typeof(ComboBox));
control.SetValue(ComboBox.ItemsSourceProperty, DummyClassCollection);
control.SetValue(ComboBox.DisplayMemberPathProperty, "DisplayValue");
//
//Some binding to connect ComboBox Selectedvalue to DataTable values
//
dataTemplate.VisualTree = control;
templateColumn.CellTemplate = dataTemplate;
templateColumn.Header = "DummyColumn";
dgGrid.Columns.Add(templateColumn);
DataTable table = new DataTable();
table.Columns.Add("DummyColumn");
table.Rows.Add(1);
table.Rows.Add(2);
dgGrid.AutoGenerateColumns = false;
dgGrid.ItemsSource = table.DefaultView;
}
}
Here is all you need...
control.SetValue(ComboBox.DisplayMemberPathProperty, "DisplayValue");
control.SetValue(ComboBox.SelectedValuePathProperty, "SelectedValue");
control.SetValue(ComboBox.SelectedValueProperty, new Binding("DummyColumn"));

Add image to ListView C# WPF (without xaml)

How can I make an image item in ListView? I need to do it without xaml, only C#. I was surfing about 40 min about it and have nothin found.
I've tried a lot of things and i stopped here
in first column i see just "System.Windows.Controls.StackPanel".
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
GridView grView = new GridView();
GridViewColumn gwCol1 = new GridViewColumn();
GridViewColumn gwCol2 = new GridViewColumn();
gwCol1.Header = "Avatar";
gwCol2.Header = "Name";
gwCol2.DisplayMemberBinding = new Binding("name");
gwCol1.DisplayMemberBinding = new Binding("stack");
grView.Columns.Add(gwCol1);
grView.Columns.Add(gwCol2);
listView1.View = grView;
//
var list = new List<XData>();
listView1.ItemsSource = list;
//
BitmapImage image1 = new BitmapImage(new Uri(#"C:\Users\montana\OneDrive\Pictures\Saved Pictures\WVQfZqY.jpg"));
Image img = new Image();
img.Width = 100;
img.Height = 100;
img.Source = image1;
StackPanel stackPanel1 = new StackPanel();
stackPanel1.Orientation = Orientation.Horizontal;
stackPanel1.Children.Add(img);
list.Add(new XData() { name="hola", stack=stackPanel1 });
}
}
class XData
{
public string name { get; set; }
// public string url { get; set; }
public StackPanel stack { get; set; }
}
Here is something what produce wanted result.
Change XData definition to avoid having view elements there (you didn't mention MVVM, but it's good to stick to):
class XData
{
public string Name { get; set; }
public string Path { get; set; }
}
Now you can either define data template in xaml (common solution) or generate it in code behind like this:
var factory = new FrameworkElementFactory(typeof(Image));
factory.SetValue(Image.SourceProperty, new Binding(nameof(XData.Path)));
factory.SetValue(Image.WidthProperty, 100.0);
factory.SetValue(Image.HeightProperty, 100.0);
var dataTemplate = new DataTemplate { VisualTree = factory };
Data template can be as complicated as you like, but obviously defining it in xaml and then loading with FindResource() is way easier, consider to use this option instead.
And then this datatemplate has to be specified as CellTemplate like this:
GridView grView = new GridView();
grView.Columns.Add(new GridViewColumn { Header = "Avatar", CellTemplate = dataTemplate });
grView.Columns.Add(new GridViewColumn { Header = "Name", DisplayMemberBinding = new Binding(nameof(XData.Name)) });
listView1.View = grView;
Note: you shouldn't use DisplayMemberBinding for column with CellTemplate.
Now, finally, you can fill ListView by setting its ItemSource as usual:
var list = new List<XData>();
list.Add(new XData { Name = "hola", Path = #"c:\temp\1.jpg" });
list.Add(new XData { Name = "hola2", Path = #"c:\temp\2.png" });
listView1.ItemsSource = list;

How to change Font/Color/Size in Xamarin C#

I'm making an Hybrid application in C#/Xamarin, and i want to make a custom menu for all applications(iOS, Android, Windows Phone).
So, I create a MasterPage to be my Menu.
public MasterPage()
{
InitializeComponent();
var masterPageItems = new List<MenuItem>();
masterPageItems.Add(new MenuItem
{
Title = "AdministraĆ§Ć£o",
});
masterPageItems.Add(new MenuItem
{
Title = "Meus Dados",
IconSource = "contacts.png",
TargetType = typeof(MeusDados),
});
masterPageItems.Add(new MenuItem
{
Title = "Dados Cadastrais",
IconSource = "contacts.png",
TargetType = typeof(MeusNegocios),
});
var listView = new ListView
{
ItemsSource = masterPageItems,
ItemTemplate = new DataTemplate(() =>
{
var imageCell = new ImageCell();
imageCell.SetBinding(TextCell.TextProperty, "Title");
imageCell.SetBinding(ImageCell.ImageSourceProperty, "IconSource");
return imageCell;
}),
VerticalOptions = LayoutOptions.FillAndExpand,
SeparatorVisibility = SeparatorVisibility.None
};
Padding = new Thickness(0, 20, 0, 0);
Content = new StackLayout
{
VerticalOptions = LayoutOptions.Fill,
Children = {
listView
}
};
}
This is the MenuItem:
public class MenuItem
{
public string Title { get; set; }
public string IconSource { get; set; }
public Type TargetType { get; set; }
public string Parameter { get; set; }
}
So now I want to change the size of content page, font, font color, font size in C#. How should I do that?
Xamarin Forms doc on Fonts:
Fonts: https://developer.xamarin.com/guides/xamarin-forms/user-interface/text/fonts/
Example:
var about = new Label {
FontSize = Device.GetNamedSize (NamedSize.Medium, typeof(Label)),
FontAttributes = FontAttributes.Bold,
Text = "Medium Bold Font"
};
I do note that you are using an ImageCell, which does not have the Font properties but only a TextColor and DetailColor property. Also there are no properties to get the underlying Labels in the ImageCell, so your best bet if you want full customization is to create your own ViewCell and add the Image and the Labels to the ViewCell. Then you can style your Labels with the Font properties.
Alternately, you can use Themes, which is in Preview: https://developer.xamarin.com/guides/xamarin-forms/themes/
StyleClass
The StyleClass property allows a view's appearance to be changed according to a definition provided by a theme.

How to add value to checkedListBox items

Is it possible to add to checkedListBox item also value and title
checkedListBox1.Items.Insert(0,"title");
How to add also value?
checkedListBox1.Items.Insert(0, new ListBoxItem("text", "value"));
Try setting the DisplayMember and ValueMember properties. Then you can pass an anonymous object like so:
checkedListBox1.DisplayMember = "Text";
checkedListBox1.ValueMember = "Value";
checkedListBox1.Items.Insert(0, new { Text= "text", Value = "value"})
Edit:
To answer your question below, you can create a class for your item like so:
public class MyListBoxItem
{
public string Text { get; set; }
public string Value { get; set; }
}
And then add them like this:
checkedListBox1.Items.Insert(0, new MyListBoxItem { Text = "text", Value = "value" });
And then you can get the value like this:
(checkedListBox1.Items[0] as MyListBoxItem).Value

Bind Object Model to UI in xamarin forms

I have an object model class ( desarlise json to object model ) , i want to use binding to attach the object model to the UI using xamarin forms.
P.S not natively nor XAML but through code.
Have search the internet but its getting more and more confusing
Any help will be anxiously helpful
Thanks
Your question is a bit unclear, but here's an example of data binding for Xamarin.Forms in code.
//INPC implementation removed in this sample
public class PersonViewModel
{
public string FirstName {get;set;}
public string LastName {get;set;}
}
var person = new PersonViewModel {
FirstName = "John",
LastName = "Doe",
};
var first = new Label ();
first.SetBinding (Label.TextProperty, "FirstName");
var label = new Label ();
label.SetBinding (Label.TextProperty, "LastName");
var personView = new StackLayout {
Orientation = StackOrientation.Horizontal,
Children = {
first,
last
}
};
personView.BindingContext = person;

Categories