I have build a dynamically-generated label/checkbox-List.
The label-content gets his content from a list with some application-names. The Checkbox(es) share a single CheckBox_Click-Event, that is triggered when i hit one of the checkboxes. The Problem i got now is, i can't identify which checkbox is clicked. Because i generate the controls i can't put a name through binding behind the controls. I'm not-so-experienced in creating gui's through code. Hope you guys can help me a bit.
// This part builds my label/combo-List through a FileInfo-List
Fields = new System.Collections.ObjectModel.ObservableCollection<Field>();
foreach (var app in GetPrograms())
{
Fields.Add(new Field() {Name = app.Name, Length = 100, Required = true});
}
FieldsListBox.ItemsSource = Fields;
// Here i got the Click-Event.. but i can't identify which Checkbox is clicked
private void CheckBox_Click(object sender, RoutedEventArgs e)
{
CheckBox senderChk = sender as CheckBox;
switch (senderChk.Name)
{
//case "checkBox1": // do something
//case "checkBox2": // do something
}
}
<!-- And finally the xaml-Code, note the Bindings on label and checkbox -->
<Grid>
<ListBox x:Name="FieldsListBox">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Label Content="{Binding Name}" VerticalAlignment="Center"></Label>
<CheckBox IsChecked="{Binding Checked}" Click="CheckBox_Click" Margin="5,0,0,0"></CheckBox>
</StackPanel>
Because i already have a list of filenames, i thought i can bind the names on the checkboxes, so i know which checkbox was clicked and can manage the right programmname.
You did this to bind the checked propierty to the comboBox.
<CheckBox IsChecked="{Binding Checked}" ... ></CheckBox>
Do the same and Bind the propierty Uid (used to identify controls in WPF) of the combobox like this:
<CheckBox ... Uid="{Binding Name}" ... ></CheckBox>
and use it in your switch.
Related
I am building an app that will return data from database based on the items that are checked on check box. I have successfully displayed data from database by binding the data. Like this:
XAML:
<ListBox x:Name="listBox1" ItemsSource="{Binding}" HorizontalAlignment="Left" Height="52" Margin="141,264,0,0" VerticalAlignment="Top" Width="307" SelectionMode="Multiple">
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox x:Name="checkBox1" IsChecked="{Binding IsSelected}" Content="{Binding NacinGrejanja}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
C#:
private void Window_Loaded_1(object sender, RoutedEventArgs e)
{
Dataset1 ds= new Dataset1 ();
GrejanjeTableAdapter gta = new GrejanjeTableAdapter();
gta.Fill(ds.Grejanje);
listbox1.DataContext = ds.Grejanje;
}
But I am unable to figure out how to extract string values from checked values and then again search for those values in database. I can't access any of the properties for checkBox1 through code.
Also I would want first to check if any of the checkbox items is checked in the first place.
You can use following linq:
ds.Grejanje.Where(item => item.IsSelected == true);
It will return the list of items which are checked.
I have such a listbox like below:
<ListBox x:Name="listBox" HorizontalAlignment="Left" Height="385" Margin="21,138,0,0" VerticalAlignment="Top" Width="273" ItemsSource="{Binding Path=locationList}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Button Name="btnDelete" Click="btnDelete_Click" Width="15" Height="15" HorizontalAlignment="Center" VerticalAlignment="Center" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Content="x" />
<CheckBox Name="checkBox" />
<TextBlock Name="textBox" Text="{Binding}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
And what I would like to do is to set checkbox for specific item this listbox.
I am trying to do it:
private void button4_Click(object sender, RoutedEventArgs e)
{
for(int i = 0; i < listBox.Items.Count; i++)
{
listBox.Items[i].checkBox = false;
}
}
I know I am doing an error. I would like to cast it to object of item and then set an item's property (this checkbox) to false. May anyone correct me ? Thank you in advance.
edit:
Before I was trying to do it this way:
foreach (var item in listBox.SelectedItems)
{
item.
}
but all possibilities I have got are just standard methods: Equals, GetHashCode, GetType, ToString... How I may refer to checkbox ?
Moreover I will supply my question with the insight. I would like to find a specific item by text which is in line in listbox (item) and then change checkbox for this item (same row in listbox).
Second logic to be implemented is to set all rows to selected or unselected (this is what I am trying to do now).
Thank you for response.
for (int i = 0; i < listBox.Items.Count; i++)
{
var item = listBox.ItemContainerGenerator.ContainerFromItem(listBox.Items[i]) as ListBoxItem;
var template = item.ContentTemplate as DataTemplate;
ContentPresenter myContentPresenter = FindVisualChild<ContentPresenter>(item);
CheckBox myCheckBox = (CheckBox)template.FindName("checkBox", myContentPresenter);
myCheckBox.IsChecked = true;
}
Likewise you can find the TextBlock with (note, you named it "textBox" not "textBlock")
TextBlock myTextBlock = (TextBlock)template.FindName("textBox", myContentPresenter);
FindVisualChild can be found here FindVisualChild reference issue
I cannot find any examples to make me understand how and if I can change the databind in c# at the click of a button on, in my case a toggleswitch, Basically I have 32 buttons in my app and those 32 buttons act the same but need different text with-in them depending on some toggle switches they are currently databinded so the text can be saved and retrieved from local storage but what values it gets depends on the state of these toggle switches.
So I currently have :
<Button x:Name="_ovButton1" Content="{Binding Source={StaticResource AppSettings}, Path=ovName1_1Value, Mode=TwoWay}" Margin="2,0,250,0" VerticalAlignment="Top" FontSize="14" Height="72" FontWeight="Bold" MouseLeftButtonUp="_ovButton1_MouseLeftButtonUp" MouseLeftButtonDown="_ovButton1_MouseLeftButtonDown" ClickMode="Hover" Hold="_ovButton1_Hold"/>
and I want when a user changes the state of a toggleswitch to change the
{StaticResource AppSettings}, Path=ovName1_1Value, Mode=TwoWay}
to for example:
{StaticResource AppSettings}, Path=ovName1_2Value, Mode=TwoWay}
but I cannot find any example that shows how to do that in c#
what code do I need to do that?
You can specify the target of databinding in code like this:
MyData myDataObject = new MyData(DateTime.Now);
Binding myBinding = new Binding("MyDataProperty");
myBinding.Source = myDataObject;
myText.SetBinding(TextBlock.TextProperty, myBinding);
See more at http://msdn.microsoft.com/en-us/library/ms742863.aspx
-- Edit Note I don't have access to a WP8 Emulator to test this ---
In the view model it looks like this:
public List<string> Members
{
get { return _Members; }
set { _Members = value; OnPropertyChanged(); }
}
public MainVM()
{
// Simulate Asychronous access, such as to a db.
Task.Run(() =>
{
Thread.Sleep(2000);
Members = new List<string>() {"Alpha", "Beta", "Gamma", "Omega"};
});
}
The code behind on the main page sets the datacontext (shared with all the child controls) as such:
public MainWindow()
{
InitializeComponent();
// Set the windows data context so all controls can have it.
DataContext = new MainVM();
}
The Mainpage Xaml to bind to members is like this
<Button Height="30"
Width="80"
Margin="10"
DataContext="{Binding Members}"
Content="{Binding Path=[0] }" />
<Button Height="30"
Width="80"
Margin="10"
DataContext="{Binding Members}"
Content="{Binding Path=[1] }" />
<Button Height="30"
Width="80"
Margin="10"
DataContext="{Binding Members}"
Content="{Binding Path=[2] }" />
<Button Height="30"
Width="80"
Margin="10"
DataContext="{Binding Members}"
Content="{Binding Path=[3] }" />
The result is this visually:
I based this on my blog article Xaml: ViewModel Main Page Instantiation and Loading Strategy for Easier Binding for more info and a fuller example.
I think your best bet is going to be to use a collection of strings and bind to that collection. You can either change the collection when a toggle is switched, or keep 6 collections and bind to the collection that is for the toggle.
Xaml:
<ItemsControl x:Name="Buttons" ItemsSource="{Binding ButtonTextCollection}">
<ItemsControl.ItemsPanel>
<toolkit:WrapPanel/>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Width="100" Height="70" Content="{Binding}" Click="OnButtonClick"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Your code-behind would have the event handler for your button click
private void OnButtonClick(object sender, RoutedEventArgs e)
{
var text = ((Button) sender).Content.ToString();
// Send the text
}
Your ViewModel would hold the ButtonTextCollection property and would change based on the toggle.
public ICollection<string> ButtonTextCollection
{
get { return _buttonTextCollection; }
set
{
_buttonTextCollection = value;
OnPropertyChanged("ButtonTextCollection");
}
}
When you want to change the text, you would change the ButtonTextCollection
public void ChangeButtonText()
{
ButtonTextCollection = new Collection<string> {"A", "B",...};
}
I am building a windows store app and due to UI problems I have to implement checkbox inside combobox.I am stucked at following problem:I want to display the checked Item in "Combobox with Checkbox" .
What I want to do :
http://blogs.microsoft.co.il/blogs/justguy/image_2827F1EB.png
<ComboBox x:Name="cb2"
DropDownOpened="cb2_DropDownOpened_1"
DropDownClosed="cb2_DropDownClosed_1"
SelectionChanged="cb2_SelectionChanged_1"
Width="310"
ItemsSource="{Binding Members}"
DisplayMemberPath="{Binding Name}"
Height="50" BorderBrush="#FF0A2562"
Tag="{Binding index}"
>
<ComboBox.ItemTemplate>
<DataTemplate>
<CheckBox
Background="Black"
BorderBrush="Black"
Tag="{RelativeSource TemplatedParent}"
Content="{Binding Name}"
IsChecked="{Binding Path=IsSelected,Mode=OneWay}"
Unchecked="CheckBox_Unchecked_1"
Click="CheckBox_Click"
/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
Code Behind:
private void CheckBox_Click(object sender, RoutedEventArgs e)
{
CheckBox chk = (CheckBox)sender;
string k =(string) chk.Content;
chkstr.Add(k);
}
private void CheckBox_Unchecked_1(object sender, RoutedEventArgs e)
{
CheckBox chk = (CheckBox)sender;
string k = (string)chk.Content;
chkstr.Remove(k);
// vl.selectedmembers.Remove(key);
}
In ComboBox Standard Template defined by Microsoft add a TextBlock in ContentPresenter.
Bind the Text Property of TextBlock with string.Now you can add the checked Items to string by converting the items to string explicitly.
#Patrick : ItemTemplate and ItemContainerStyle both will work.
You need to retemplate the ComboBoxItem. Specify ComboBox.ItemContainerStyle instead of ComboBox.ItemTemplate. Inside of ComboBox.ItemContainerStyle, have a setter for Template. Copy the default template and add a CheckBox. Template-bind CheckBox.IsChecked to IsSelected, or animate IsChecked to true using an object animation in the Selected visual state.
Your approach won't work since IsSelected is a property on the ComboBoxItem container, not the data context.
My code is as below
<ListBox x:Name="lstbxRefMarket" Margin="5,5,5,5" BorderThickness="0" Height="100" VerticalAlignment="Stretch">
<ListBox.ItemTemplate>
<HierarchicalDataTemplate>
<CheckBox Name="chkbxRefMarket" Content="{Binding Market}" CommandParameter="{Binding MarketId}" Tag="{Binding MarketId}" IsChecked="{Binding Checked}" Checked="chkbxRefMarket_Checked" Unchecked="chkbxRefMarket_Unchecked" Foreground="Blue"/>
</HierarchicalDataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Now in code behind I need to uncheck the particular checkbox with MarketId as 8 from chkbxRefMarket list
As you see from the code checkbox will be having CommandParameter ,Tag as MarketId
How can I find the particular checkbox with that market id in the list .
Why not simply find the right item and set its Checked property. The associated CheckBox is bound to that property and will automatically be unchecked.
The code below assumes that your data item class is MyItem.
IEnumerable<MyItem> items = lstbxRefMarket.Items.OfType<MyItem>();
MyItem item = items.FirstOrDefault(i => i.MarketId == 8);
if (item != null)
{
item.Checked = false;
}