How to Enable/Disable button in wpf - wpf

I Have 2 button , Start And capture. I want disable capture button on form load and enable start. and on after click on start disable start button and enable capture.
Please help me.
Thanks in advance
Edit
<Grid>
<Button Content="Button" Height="77" HorizontalAlignment="Left" Margin="92,151,0,0" Name="button1" VerticalAlignment="Top" Width="109">
<Button.Background>
<ImageBrush ImageSource="/WpfApplication1;component/Images/images.jpg" />
</Button.Background>
</Button>
<Button Content="Button" Height="77" HorizontalAlignment="Left" Margin="229,151,0,0" Name="button2" VerticalAlignment="Top" Width="112" IsEnabled="False" >
<Button.Background>
<ImageBrush ImageSource="/WpfApplication1;component/Images/images.jpg" />
</Button.Background>
</Button>
</Grid>

<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Button Name="BStart" Content="Start" Width="100" Height="50" HorizontalAlignment="Left" Click="BStart_Click" />
<Button Name="BCapture" Content="Capture" Width="100" Height="50" HorizontalAlignment="Right" IsEnabled="False" />
</Grid>
</Window>
you can disable Capture by xaml and then enable it by writing code in c#.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void BStart_Click(object sender, RoutedEventArgs e)
{
BStart.IsEnabled = false;
BCapture.IsEnabled = true;
}
}
}
for enable and disable use IsEnabled Property. and for clicking on the button use Click event.

Set IsEnabled="False" to disable the button
<Button Name="btn" IsEnabled="False" Content="press"/>
Set IsEnabled="True" to enable the button
<Button Name="btn" IsEnabled="True" Content="press"/>
Hope this helps

You should store current state in some variable (e.g. _capturing). When variable changing, you refresh IsEnabled property.
Xaml code:
<Button Content="Start" Name="StartButton" Grid.Row="0" Click="StartButton_Click" />
<Button Content="Capture" Name="CaptureButton" Grid.Row="1" Click="CaptureButton_Click"/>
C# code:
public partial class MainWindow : Window
{
private bool _capturing;
public MainWindow()
{
InitializeComponent();
// Some code
_capturing = false;
UpdateButtons();
}
private void StartButton_Click(object sender, RoutedEventArgs e)
{
// Some code
_capturing = true;
UpdateButtons();
}
private void CaptureButton_Click(object sender, RoutedEventArgs e)
{
// Some code
UpdateButtons();
}
private void UpdateButtons()
{
StartButton.IsEnabled = !_capturing;
CaptureButton.IsEnabled = _capturing;
}
}
UPDATE
You should add click handler and your xaml code will work:
<Button Click="StartButton_Click" Content="Button" Height="77" HorizontalAlignment="Left" Margin="92,151,0,0" Name="button1" VerticalAlignment="Top" Width="109">
<Button.Background>
<ImageBrush ImageSource="/WpfApplication1;component/Images/images.jpg" />
</Button.Background>
</Button>
<Button Click="CaptureButton_Click" Content="Button" Height="77" HorizontalAlignment="Left" Margin="229,151,0,0" Name="button2" VerticalAlignment="Top" Width="112" IsEnabled="False" >
<Button.Background>
<ImageBrush ImageSource="/WpfApplication1;component/Images/images.jpg" />
</Button.Background>
</Button>

Yes I got my answer. Just make simeple solution
btnhide.visibility= system.visibility. hidden;

There are two ways to disable a button In C# WPF.
In .xaml File
Using IsEnabled="False". If you set False to IsEnabled attribute, then your button will be disabled by default.
In .cs File
ButtonName.IsEnabled = false; If you set IsEnabled property as false for the button, it will disable the button

Related

WPF ListBox grow up on Event Handler?

I am extremely new using C# and that's far away from my mechanical skills ... I have very basic knowledge in C# but I am really willing to push the knowledge effort. Thanks to keep it in minde.
I creating some sort of application/ERP to help with working with my suppliers. The final goal is to create a list of suppliers, their skills, consult RFQ, update RFQ, send emails, ... I have been doing it in Excel VBA in the past but now I am willing to build up something stronger (and also willing to learn something new ...).
First of all, I am willing to create a ListBox with different kind of processes. I would like this ListBox to only show one ListBoxItems (one row) and when the mouse is entering into the ListBox, grow the ListBox to it's full size.
(My goal would be to ! create a ListBox with a dropdown for multiselection :=))
The dirty way I was thinking doing it is:
Create a TextBox with "Click to expand" text. When the mouse is entering the Textbox, hide it and change the listbox visibility to Visible (default visibility to Hidde);
Any thought about it ? Where should I start by ?
I will then selected multiple items in my ListBox.
Latter on, I would like to binding ListBox content to a data base (don't know how to create it on my computer).
Any help is greatly appreciated !
Cheers
Edit:
Below is my XAML code:
<Window x:Class="ERP_Fournisseurs.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:ERP_Fournisseurs"
mc:Ignorable="d"
Title="ERP Fournisseurs" Height="450" Width="800">
<Canvas>
<TabControl Height="369" Width="734" Canvas.Left="10" Canvas.Top="9">
<TabItem Header="Ajouter fournisseurs">
<Canvas Margin="0,0,0,-1">
<TextBlock Canvas.Left="10" Name="Fournisseur" TextWrapping="Wrap" Text="Nom fournisseur" Canvas.Top="16" />
<TextBox Height="23" Name="NomTXT" Canvas.Left="150" TextWrapping="Wrap" Text="Entrer nom fournisseur" Canvas.Top="14" Width="225" MouseDoubleClick="NomFournisseur_MouseDoubleClick" TextChanged="NomTXT_TextChanged" />
<TextBlock Canvas.Left="10" Name="Telephone" TextWrapping="Wrap" Text="Telephone" Canvas.Top="55"/>
<TextBox Height="23" Name="TelTXT" Canvas.Left="150" TextWrapping="Wrap" Text="Entrer téléphone fournisseur" Canvas.Top="55" Width="225" MouseDoubleClick="TelTXT_MouseDoubleClick"/>
<TextBlock Canvas.Left="10" Name="Mail" TextWrapping="Wrap" Text="Mail" Canvas.Top="84"/>
<TextBox Height="23" Name="MailTXT" Canvas.Left="150" TextWrapping="Wrap" Text="Entrer adresse e-mail" Canvas.Top="91" Width="225" MouseDoubleClick="MailTXT_MouseDoubleClick"/>
<TextBlock Canvas.Left="10" Name="Adresse" TextWrapping="Wrap" Text="Adresse" Canvas.Top="124"/>
<TextBox Height="23" Name="AdresseTXT" Canvas.Left="150" TextWrapping="Wrap" Text="Entrer adresse" Canvas.Top="127" Width="225" MouseDoubleClick="AdresseTXT_MouseDoubleClick"/>
<TextBlock Canvas.Left="10" Name="Types" TextWrapping="Wrap" Text="Types" Canvas.Top="157"/>
<TextBox Height="23" Name="TypesTXT" Canvas.Left="150" TextWrapping="Wrap" Text="Entrer types" Canvas.Top="162" Width="225" />
<TextBlock Canvas.Left="10" Name="Procédés" TextWrapping="Wrap" Text="Procédés" Canvas.Top="194"/>
<TextBlock Canvas.Left="10" Name="Matériaux" TextWrapping="Wrap" Text="Matériaux" Canvas.Top="232"/>
<TextBlock Canvas.Left="10" Name="Délais" TextWrapping="Wrap" Text="Délais" Canvas.Top="258"/>
<TextBlock Canvas.Left="10" Name="Autres" TextWrapping="Wrap" Text="Autres" Canvas.Top="289"/>
<TextBox Height="23" x:Name="AutreTXT" Canvas.Left="150" TextWrapping="Wrap" Text="Entrer types" Canvas.Top="289" Width="225" MouseDoubleClick="AutreTXT_MouseDoubleClick"/>
<Button Name="AjoutTXT" Content="Ajouter" Height="100" Width="75" Canvas.Left="563" Canvas.Top="107" Click="AjoutTXT_Click"/>
<ListBox Name="ListBoxProc" HorizontalAlignment="Left" VerticalAlignment="Top" Width="181" Height="186" Canvas.Left="409" Canvas.Top="54" Visibility="Hidden" MouseLeave="ListBoxProc_MouseLeave" MouseEnter="ListBoxProc_MouseEnter" SelectionMode="Multiple">
<ListBoxItem>TEST 1</ListBoxItem>
<ListBoxItem>TEST 1</ListBoxItem>
<ListBoxItem>TEST 1</ListBoxItem>
<ListBoxItem>TEST 1</ListBoxItem>
</ListBox>
<TextBox Height="23" Name="ProcTXT2" Canvas.Left="150" TextWrapping="Wrap" Text="Entrer types" Canvas.Top="196" Width="225" />
</Canvas>
</TabItem>
<TabItem Header="Suivi devis" >
<Canvas>
</Canvas>
</TabItem>
<TabItem Header="Liste fournisseurs" >
<Canvas>
</Canvas>
</TabItem>
</TabControl>
</Canvas>
</Window>
Below is my XAML.CS
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace ERP_Fournisseurs
{
/// <summary>
/// Logique d'interaction pour MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void NomFournisseur_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
NomTXT.Text = "";
}
private void TelTXT_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
TelTXT.Text = "";
}
private void MailTXT_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
MailTXT.Text = "";
}
private void AdresseTXT_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
AdresseTXT.Text = "";
}
private void AjoutTXT_Click(object sender, RoutedEventArgs e)
{
}
private void AutreTXT_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
AutreTXT.Text = "";
}
private void ProcTXT_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
private void NomTXT_TextChanged(object sender, TextChangedEventArgs e)
{
}
private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
private void MaterTXT_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
private void ProcTXT_MouseEnter(object sender, MouseEventArgs e)
{
}
private void ListBoxProc_MouseEnter(object sender, MouseEventArgs e)
{
ListBoxProc.Visibility = Visibility.Hidden;
}
private void ListBoxProc_MouseLeave(object sender, MouseEventArgs e)
{
ListBoxProc.Visibility = Visibility.Visible;
}
//https://www.c-sharpcorner.com/UploadFile/mahesh/listbox-in-wpf/ Binding ListBox to Data Base
}
}
What I have tried:
Asked google my solution, but it's answerless;
Tried the following code (https://www.codeproject.com/Questions/696480/How-to-make-a-ListBox-grow-on-mouseover) but not working

wpf usercontrol resizing with thumb not firing DragDelta

I have created a Usercontrol that I would like to make resizable using the thumb control. I have added my control to a Canvas and when I click on the thumb control the only events that are fired are Dragend and DragStart (in that order) and DragDelta is not even firing. I have found someone with a similar problem Thumb inside an ItemsControl not firing DragDelta event but there is no way I can ask them if they found a solution.
This is the code :
<UserControl x:Class="test.ucChair"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="53" d:DesignWidth="93" RenderTransformOrigin="0.5,0.5" Background="Beige"
>
<Grid Name="grd" Margin="0,0,0,0">
<Rectangle x:Name="rectAngle" Margin="0,0,0,0" Stroke="Black" RenderTransformOrigin="0.5,0.5" Grid.ZIndex="1000" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" MinHeight="53" /> <!-- Width="93" Height="53"-->
<TextBox x:Name="txtName" Text="OPEN" Margin="0,0,0,0" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" IsReadOnly="True" IsReadOnlyCaretVisible="False" TextWrapping="Wrap" Width="93" KeyDown="txtName_KeyDown" FlowDirection="RightToLeft" BorderThickness="0" FontSize="14" Cursor="Hand" TextAlignment="Center"/>
<Thumb Name="thmbResize" DockPanel.Dock="Right" VerticalAlignment="Bottom" Height="15" Width="15"
DragDelta="OnResizeThumbDragDelta"
DragStarted="OnResizeThumbDragStarted"
DragCompleted="OnResizeThumbDragCompleted" HorizontalAlignment="Right">
</Thumb>
</Grid>
</UserControl>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace test
{
/// <summary>
/// Interaction logic for ucChairLeft.xaml
/// </summary>
public partial class ucChair : UserControl
{
public ChairType AngleType;
//?? public int SectionID;
public ucChair()//ChairType CType)//?, int _SectionID)
{
InitializeComponent();
}
private void OnResizeThumbDragCompleted(object sender, System.Windows.Controls.Primitives.DragCompletedEventArgs e)
{
System.Diagnostics.Debug.WriteLine("DragEnd");
Mouse.Capture(null);
}
private void OnResizeThumbDragDelta(object sender, System.Windows.Controls.Primitives.DragDeltaEventArgs e)
{
System.Diagnostics.Debug.WriteLine("DragDelta");
}
private void OnResizeThumbDragStarted(object sender, System.Windows.Controls.Primitives.DragStartedEventArgs e)
{
Mouse.Capture(this);
System.Diagnostics.Debug.WriteLine("DragStart");
}
}
}
<Window xmlns:test="clr-namespace:test" x:Class="test.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="300" Width="300">
<Canvas Width="300" Height="300" Background="LightBlue">
<test:ucChair Canvas.Left="50" Canvas.Top="100" Width="50" Height="50" Background="Yellow"/>
</Canvas>
</Window>
Any help greatly appreciated!

MVVM code for a calculator in WPF

I've written a code for a simple calculator in wpf .
My MainWindow.Xaml code is..
<Window x:Class="CalculatorNew.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid ContextMenuClosing="Multi">
<TextBox x:Name="TextBox1" HorizontalAlignment="Left" Height="23" Margin="216,23,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" RenderTransformOrigin="0.679,0.552"/>
<TextBox x:Name="TextBox2" HorizontalAlignment="Left" Height="23" Margin="216,76,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" RenderTransformOrigin="0.679,0.552"/>
<TextBox x:Name="TextBox3" HorizontalAlignment="Left" Height="23" Margin="216,121,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" RenderTransformOrigin="0.679,0.552"/>
<TextBlock HorizontalAlignment="Left" Margin="68,30,0,0" TextWrapping="Wrap" Text="First Number" VerticalAlignment="Top" RenderTransformOrigin="1.137,1.259" Height="16" Width="80"/>
<TextBlock HorizontalAlignment="Left" Margin="68,128,0,0" TextWrapping="Wrap" VerticalAlignment="Top" RenderTransformOrigin="1.137,1.259" Height="16" Width="80" Text="Result"/>
<TextBlock HorizontalAlignment="Left" Margin="68,83,0,0" TextWrapping="Wrap" VerticalAlignment="Top" RenderTransformOrigin="1.137,1.259" Height="16" Width="99" Text="Second Number"/>
<Button Content="+" HorizontalAlignment="Left" Margin="73,172,0,0" VerticalAlignment="Top" Width="75" Click="Add"/>
<Button Content="-" HorizontalAlignment="Left" Margin="179,172,0,0" VerticalAlignment="Top" Width="75" Click="Sub"/>
<Button Content="*" HorizontalAlignment="Left" Margin="286,172,0,0" VerticalAlignment="Top" Width="75" Click="Multi"/>
<Button Content="/" HorizontalAlignment="Left" Margin="392,172,0,0" VerticalAlignment="Top" Width="75" Click="Div"/>
</Grid>
My MainWindowdow.Xaml.cs code is..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace CalculatorNew
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Add(object sender, RoutedEventArgs e)
{
TextBox3.Text = (System.Convert.ToDecimal(TextBox1.Text) + System.Convert.ToDecimal(TextBox2.Text)).ToString();
}
private void Sub(object sender, RoutedEventArgs e)
{
TextBox3.Text = (System.Convert.ToDecimal(TextBox1.Text) - System.Convert.ToDecimal(TextBox2.Text)).ToString();
}
private void Div(object sender, RoutedEventArgs e)
{
TextBox3.Text = (System.Convert.ToDecimal(TextBox1.Text) / System.Convert.ToDecimal(TextBox2.Text)).ToString();
}
private void Multi(object sender, RoutedEventArgs e)
{
TextBox3.Text = (System.Convert.ToDecimal(TextBox1.Text) * System.Convert.ToDecimal(TextBox2.Text)).ToString();
}
}
}
I am new to WPF and MVVM . So I am finding it a bit difficult to write it in the MVVM format .
Can someone tell me how to rewrite it in MVVM format so that I can use it as a reference for the future?
I think your question has a high chance of being closed because it doesn't demonstrate a minimum willingness to make an effort on your part. Please read a tutorial, there are plenty on the web, and try to understand the concepts first. You need at the very least to understand what a ViewModel is, and how the View relates to it (bindings).
You will probably not get working code that does exactly what you want on this site, I for one am much more interested in explaining how things work.
Anyway, in order to get what you want you need a class that acts as the ViewModel with properties that represent the concepts that you work with. You could have decimal properties that represent the operands and something that represents the operator, and commands that represent each button in the UI. Then you need bindings that link UI elements (textboxes, buttons) to the properties in the ViewModel, and you need to set an instance of the ViewModel as the DataContext of the container for the UI elements you're interested in (be it a Window, Grid or whatever). I think that pretty much sums it up...
You can use this example as a reference. https://code.google.com/p/wpf-mvvm-calculator/downloads/list

ListBox Selected Item

I am developing a wpf app. I have a database like this.
I have three columns(id,name,profession).listbox shows name column.
When the user clicks the item in listbox, i wanna show his/her profession
in textblock.
listbox works well. I have bounded it to a dataview. but how can i show his/her profession in textblock?
private void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
//What can I write here?
}
You should proably just bind the text attribute of the TextBlock to the selected item of the list box. Check this article at MSDN.
<StackPanel>
<TextBlock Width="248" Height="24" Text="Colors:"
TextWrapping="Wrap"/>
<ListBox x:Name="lbColor" Width="248" Height="56">
<ListBoxItem Content="Blue"/>
<ListBoxItem Content="Green"/>
<ListBoxItem Content="Yellow"/>
<ListBoxItem Content="Red"/>
<ListBoxItem Content="Purple"/>
<ListBoxItem Content="Orange"/>
</ListBox>
<TextBlock Width="248" Height="24" Text="You selected color:" />
<TextBlock Width="248" Height="24">
<TextBlock.Text>
<Binding ElementName="lbColor" Path="SelectedItem.Content"/>
</TextBlock.Text>
</TextBlock>
</StackPanel>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data;
using System.Data.OleDb;
namespace WpfApplication2
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public DataView view;
public DataSet ds;
public Window1()
{
InitializeComponent();
BindData();
}
public void BindData() {
OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\Information.mdb;Persist Security Info=True");
con.Open();
string sql = "Select * from Dictionary";
OleDbCommand cmd = new OleDbCommand(sql, con);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
da.Fill(ds, "Info");
view = ds.Tables[0].DefaultView;
listBox1.ItemsSource = view;
}
catch (Exception ex)
{
}}
private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
{
view.RowFilter = string.Format("Name Like '{0}%'", textBox1.Text);
}
}
}
<Window x:Class="WpfApplication2.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="490">
<Grid>
<ListBox Margin="18,77,0,83" Name="listBox1" ItemsSource="{Binding Path=Name}" HorizontalAlignment="Left" Width="213" SelectionChanged="listBox1_SelectionChanged" >
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Name}"> </TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<TextBox Height="23" Margin="18,40,0,0" Name="textBox1" VerticalAlignment="Top" TextChanged="textBox1_TextChanged" HorizontalAlignment="Left" Width="213" />
<TextBlock HorizontalAlignment="Right" Margin="0,77,42,83" Name="textBlock1" Width="185" Background="#FFE6C6C6" /><Label Height="28" HorizontalAlignment="Right" Margin="0,39,76,0" Name="label1" VerticalAlignment="Top" Width="140">Label</Label>
</Grid>
</Window>

How to access ListBox dynamically-created-items' properties from code-behind?

XAML:
<Window x:Class="WpfApp_ListBoxTest.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
<ListBox Name="lb" Margin="0,0,0,70"></ListBox>
<Button Height="23" HorizontalAlignment="Left" Margin="12,0,0,41" Name="btnAdd" VerticalAlignment="Bottom" Content="Add item" Width="75" Click="btnAdd_Click"></Button>
<TextBox Height="23" Margin="93,0,12,41" Name="txtInput" VerticalAlignment="Bottom" />
<Button Height="23" HorizontalAlignment="Left" Margin="12,0,0,12" Name="btnGet" VerticalAlignment="Bottom" Content="Get value" Width="75" Click="btnGet_Click"></Button>
<TextBox Height="23" Margin="93,0,12,12" Name="txtReturn" VerticalAlignment="Bottom" IsReadOnly="True" />
</Grid>
</Window>
Csharp:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml;
namespace WpfApp_ListBoxTest
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
TextBox txt = new TextBox();
txt.Width = 200;
txt.Text = txtInput.Text;
lb.Items.Add(txt);
}
private void btnGet_Click(object sender, RoutedEventArgs e)
{
// What do I need to write here to get the value of the Text property of the selected TextBox?
}
}
}
And screenshot: (Sorry I'm not allowed to post picture directly)
http://i825.photobucket.com/albums/zz180/mGlushed/get_listbox_item_property.png
(In the picture above, I want to get the value "b" when I click the "Get value" button.)
I would like to know if there is a simple way to achieve this.
I'm new to WPF, so I only know to do this the long way, which is: Create an array. Everytime a new TextBox is created, add it into the array. Then access the TextBox'es through the array. But that doesn't sound very optimal, I think.
The 'WPF Way' of doing what you want is to use data binding:
Define a class with a string property called Text.
Create a collection of that class.
Bind your list box ItemsSource to the collection.
Create a DataTemplate that shows a TextBox with its Text property bound using {Binding Path=Text}.
In btnAdd_Click add an item to the collection (not directly to the ListBox)
In btnGet_Click you can get the text entered by casting ListBox.SelectedItem to your class and getting its Text property.
Example:
The simple class:
public class VMObject
{
public VMObject(string text)
{
Text = text;
}
public string Text { get; set; }
}
The window code-behind:
public partial class Window1 : Window
{
public ObservableCollection<VMObject> VM { get; set; }
public Window1()
{
VM = new ObservableCollection<VMObject>();
InitializeComponent();
}
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
VM.Add(new VMObject(txtInput.Text));
}
private void btnGet_Click(object sender, RoutedEventArgs e)
{
if (lb.SelectedItem == null)
MessageBox.Show("No item is selected!");
txtReturn.Text = ((VMObject)lb.SelectedItem).Text;
}
}
The XAML:
<Window x:Class="lbtest.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Name="Window"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<DataTemplate x:Key="TextBoxTemplate">
<TextBox Text="{Binding Path=Text}"/>
</DataTemplate>
</Window.Resources>
<Grid>
<ListBox Name="lb" Margin="0,0,0,70"
ItemsSource="{Binding ElementName=Window, Path=VM}"
ItemTemplate="{StaticResource TextBoxTemplate}" />
<Button Height="23" HorizontalAlignment="Left" Margin="12,0,0,41"
Name="btnAdd" VerticalAlignment="Bottom"
Content="Add item" Width="75" Click="btnAdd_Click" />
<TextBox Height="23" Margin="93,0,12,41"
Name="txtInput" VerticalAlignment="Bottom" />
<Button Height="23" HorizontalAlignment="Left" Margin="12,0,0,12"
Name="btnGet" VerticalAlignment="Bottom"
Content="Get value" Width="75" Click="btnGet_Click" />
<TextBox Height="23" Margin="93,0,12,12"
Name="txtReturn" VerticalAlignment="Bottom" IsReadOnly="True" />
</Grid>
</Window>
for a checkbox item:
private void chk_Checked(object sender, RoutedEventArgs e)
{
CheckBox chk = (CheckBox)sender;
MessageBox.Show(chk.Content.ToString());
}
No need for TextBox:s. ListBox handle strings fine.
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
// No need to create TextBox, ListBox handle strings fine.
lb.Items.Add(txtInput.Text);
}
private void btnGet_Click(object sender, RoutedEventArgs e)
{
// No selection, but button has been pressed.
if(lb.SelectedItem == -1)
return;
// Get selected item.
txtReturn.Text = (string)lb.SelectedItem;
/* If you change ListBox selection mode to multiple
* you can get all selected items by using foreach loop.
foreach (Object selected in lb.SelectedItems)
{
txtReturn.Text += (string) selected;
}
*/
}
If you just want to get the Text property of the selected TextBox (admiting your ListBox is in single selection mode) it it quite simple:
private void btnGet_Click(object sender, RoutedEventArgs e)
{
if(lb.SelectedItem != -1)
{
TextBox selectedTextBox = (TextBox)lb.SelectedItem;
txtReturn.Text = selectedTextBox.Text;
}
}
But if you want to implement the pretty WPF way, you should follow the Aviad P. solution, my solution do it well too.
Regards.
EDIT: If do not have a real need of TextBox functionalities, but only a string container, so follow Tuukka's solution.

Resources