here i m using a wpf ComboBox control and binding it using the datasource.
but my combobox is unable to set default seletion of first index which i give
manualy during the time to binding. here my code shown below can any one tell me how to set default item in combox box.
//Xaml
<ComboBox Height="23" HorizontalAlignment="Left" Margin="142,11,0,0" Name="cmbProductType" VerticalAlignment="Top" Width="180" ItemsSource="{Binding}" />
//Code
private void Window_Loaded(object sender, RoutedEventArgs e)
{
ClsControl.GetProductTypeList(cmbProductType);
}
public static void GetProductTypeList(ComboBox ddlProductType)//Add By Sandeep On 11-03-2013
{
try
{
DataTable dtProductType = null;
try
{
ClsDataLayer objDataLayer = new ClsDataLayer();
dtProductType = objDataLayer.ExecuteDataTable("COMNODE_PROC_GetProductTypeList");
if (dtProductType != null && dtProductType.Rows.Count > 0)
{
DataRow drCardType = dtProductType.NewRow();
drCardType[0] = -1;
drCardType[1] = "< -- Select Card Type -- >";
ddlProductType.SelectedValue = -1;
dtProductType.Rows.InsertAt(drCardType, 0);
ddlProductType.ItemsSource = dtProductType.DefaultView;
ddlProductType.DisplayMemberPath = "PRODUCT_TYPE";
ddlProductType.SelectedValuePath = "PRODUCT_TYPE_ID";
}
}
catch (Exception)
{
throw;
}
}
catch
{
}
}
Try updating your XAML to this:
<ComboBox Height="23"
HorizontalAlignment="Left"
Margin="142,11,0,0"
Name="cmbProductType"
VerticalAlignment="Top"
Width="180"
ItemsSource="{Binding}"
IsSynchronizedWithCurrentItem="True" />
Also, use SelectedIndex instead when you select the item:
ddlProductType.SelectedIndex = 0;
dtProductType.Rows.InsertAt(drCardType, 0);
ddlProductType.ItemsSource = dtProductType.DefaultView;
ddlProductType.DisplayMemberPath = "PRODUCT_TYPE";
ddlProductType.SelectedValuePath = "PRODUCT_TYPE_ID"
Related
I am creating UWP app, and I maked external arrow "marker" of selected item in listview...
Like this:
I have managed to achieve this with next code:
var current = lvMain.Items.FirstOrDefault(a => (a as MyModel).Selected) as MyModel;
ListViewItem selected = lvMain.ContainerFromItem(current) as ListViewItem;
GeneralTransform generalTransform1 = gvEpg.TransformToVisual(selected);
Point currentPoint = generalTransform1.TransformPoint(new Point());
In Scroll change event I am calling this and set the arrow position by the Point of my item. And this is working.
But, I want to simplified this. Is there any kind of binding or something like that, that would make arrow always follow the item?
Here's the sample.
XAML MainPage:
<Page.Resources>
<DataTemplate x:Key="DataTemplate">
<Canvas Height="80" Width="200">
<TextBlock Text="{Binding}"/>
</Canvas>
</DataTemplate>
</Page.Resources>
<StackPanel Orientation="Horizontal">
<ListView x:Name="ListView" Width="400"
SelectionChanged="ListView_OnSelectionChanged"
ItemTemplate="{StaticResource DataTemplate}"/>
<Canvas x:Name="ParentCanvas">
<Image x:Name="Arrow"
Stretch="UniformToFill" Width="200" Height="80"
Source="Assets/Red_Left_Arrow.png"/>
</Canvas>
</StackPanel>
Code behind:
private readonly List<string> _names = new List<string>();
private Visual _rectangleVisual;
private Visual _parentVisual;
public MainPage()
{
InitializeComponent();
Loaded += MainPage_Loaded;
}
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
for (int i = 0; i < 32; i++)
{
_names.Add("item " + i);
}
ListView.ItemsSource = _names;
_parentVisual = ElementCompositionPreview.GetElementVisual(ParentCanvas);
_rectangleVisual = ElementCompositionPreview.GetElementVisual(Arrow);
var border = VisualTreeHelper.GetChild(ListView, 0) as Border;
var scrollViewer = border.Child as ScrollViewer;
var scrollerProperties = ElementCompositionPreview.GetScrollViewerManipulationPropertySet(scrollViewer);
var offsetExpressionAnimation = _rectangleVisual.Compositor.CreateExpressionAnimation("Scroller.Translation.Y");
offsetExpressionAnimation.SetReferenceParameter("Scroller", scrollerProperties);
_rectangleVisual.StartAnimation("Offset.Y", offsetExpressionAnimation);
}
private void ListView_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
var listViewItem = ListView.ContainerFromItem(ListView.SelectedItem) as ListViewItem;
var listItemVisual = ElementCompositionPreview.GetElementVisual(listViewItem);
_parentVisual.Offset = new Vector3(_parentVisual.Offset.X, listItemVisual.Offset.Y, 0);
}
Looks like what you asked for:
Im tring to get Selected row item.
I have been readed that it should be worked :
<DataGrid ItemsSource="{Binding Path=Customers}"
SelectedItem="{Binding Path=SelectedCustomer, Mode=TwoWay}"/>
Customer customer = (Customer)myDataGrid.SelectedItem;
In the first xaml - I put it, it doesnt error or something I just dont know how to use it.. How in the c# code I can get the selected row ?
In the C# line code It error. The visual studio doesn't exist Customer.
I would thankfull to help. :) Thanks.
rly hard to know what exactly you wanted :) but here is an example I just put togetter on how to drag info out of the datagrid.
Did not implament alot of those bindings in it so this is pure getting the info.
Xaml
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<DataGrid Grid.Row="0" Name="dg"/>
<Button Grid.Row="1" Name="btn" Click="btn_Click" />
</Grid>
Codebehind
List<SomeInfo> list = new List<SomeInfo>();
public MainWindow()
{
InitializeComponent();
list.Add(new SomeInfo() { Name = "PC", Description = "Computer", ID = 1 });
list.Add(new SomeInfo() { Name = "PS", Description = "Playstation", ID = 2 });
list.Add(new SomeInfo() { Name = "XB", Description = "Xbox", ID = 3 });
this.dg.ItemsSource = list;
}
public class SomeInfo
{
public string Name { get; set; }
public string Description { get; set; }
public int ID { get; set; }
}
private void btn_Click(object sender, RoutedEventArgs e)
{
if (dg.SelectedIndex != -1)
{
DataGrid dataGrid = sender as DataGrid;
DataGridRow row = (DataGridRow)dg.ItemContainerGenerator.ContainerFromIndex(dg.SelectedIndex);
DataGridCell RowColumn = dg.Columns[0].GetCellContent(row).Parent as DataGridCell;
btn.Content = ((TextBlock)RowColumn.Content).Text;
}
}
the btn_click does all the gathering info stuff where the last 2 makes my datagrid for testing.
Hope it will help you out :)
------------------Edit--------------------------
from the comment this below is what you would need only
private void btn_Click(object sender, RoutedEventArgs e)
{
if (dg.SelectedIndex != -1)
{
DataGrid dataGrid = sender as DataGrid;
DataGridRow row = (DataGridRow)dg.ItemContainerGenerator.ContainerFromIndex(dg.SelectedIndex);
DataGridCell RowColumn = dg.Columns[0].GetCellContent(row).Parent as DataGridCell;
btn.Content = ((TextBlock)RowColumn.Content).Text;
}
}
dg = your datagrid
dg.Columns[0] = change 0 into what column you want
info from btn.Content = what you want the content to be
--------------EDIT 2------------
To get the selected row's index all you need is
int index = dg.SelectedIndex;
btn.Content = index;
or if you dont want to store the integar
btn.Content = dg.SelectedIndex;
The grid defined in a very incomplete.
Council to explicitly all columns that compose it with the individual binding
In this case I used the event doubleClick but you have to choose the right event to you
By code for example try this:
In XAML add:
<DataGrid x:Name="MyDataGrid" x:FieldModifier="public" MouseDoubleClick="MyDataGrid_MouseDoubleClick" ItemsSource="{Binding Path=Customers}"
SelectedItem="{Binding Path=SelectedCustomer, Mode=TwoWay}"/>
And in behind c# code this:
private void MyDataGrid_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
if (sender != null)
{
DataGrid grid = sender as DataGrid;
if (grid != null && grid.SelectedItems != null && grid.SelectedItems.Count == 1)
{
var selectedRow = grid.SelectedItem as MyObject;
try
{
Mouse.OverrideCursor = Cursors.Wait;
//TODO YOUR OPERATION ON selectdRow
}
finally
{
Mouse.OverrideCursor = null;
}
}
}
}
I would like to know how to disable ComboBox DropDown Button Programmatically. I had seen many similar subjects but all of these have a XAML solution.
By the way, if someone know how to disable all ComboBox control design and left visible only item template it can be helpful too.
UPDATE
its my XAML definition
<ComboBox Name="lang_ComboBox" SelectionChanged="LanguageSelection_ComboBox_SelectionChanged"/>
And there is how i use it:
String text = "dorf";
BitmapImage image = new BitmapImage(new Uri("http://img88.imageshack.us/img88/4351/butchermi4.png"));
lang_ComboBox.Width = 100;
lang_ComboBox.Height = 30;
Grid sp;
for (int i = 0; i < 5; i++)
{
ColumnDefinition gridCol1 = new ColumnDefinition();
gridCol1.Width = new GridLength(30.0);
ColumnDefinition gridCol2 = new ColumnDefinition();
gridCol2.Width = new GridLength(70.0);
sp = new Grid()
{
Width = 100,
Height = 30
};
Image im = new Image()
{
Source = image,
Width = 25,
Height = 25
};
Label la = new Label()
{
Content = text
};
sp.ColumnDefinitions.Add(gridCol1);
sp.ColumnDefinitions.Add(gridCol2);
Grid.SetColumn(im, 0);
Grid.SetColumn(la, 1);
sp.Children.Add(la);
sp.Children.Add(im);
lang_ComboBox.Items.Add(sp);
}
UPDATE 2
Hmmm I get it now, I use wrong word. It should be "Hide" control design and still can choose from a list. My bad sorry. But i know how i can solve it with Anatoliy Nokolaev's Code. To hide control design i use:
ToggleButton dropDownButton = GetFirstChildOfType<ToggleButton>(lang_ComboBox);
dropDownButton.Visibility = System.Windows.Visibility.Collapsed;
Unwanted behavior is now only that i cant show combobox dropdownmenu, but I'll invoke it programmatically by add on click event and should be good.
If there is any easiest way to do this tell me :).
To disable only the ToggleButton in ComboBox programmatically, you need to find this in the ComboBox control using VisualTreeHelper and assign a property IsEnabled to false, like this:
XAML
<Window x:Class="DisableComboBoxButton.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"
Loaded="Window_Loaded">
<StackPanel>
<ComboBox Name="comboBox"
Width="100"
Height="25"
SelectedIndex="0">
<ComboBoxItem>Test1</ComboBoxItem>
<ComboBoxItem>Test2</ComboBoxItem>
<ComboBoxItem>Test3</ComboBoxItem>
</ComboBox>
<ComboBox Name="AllComboBoxDisabled"
Width="100"
Height="25"
IsEnabled="False"
SelectedIndex="0">
<ComboBoxItem>Test1</ComboBoxItem>
<ComboBoxItem>Test2</ComboBoxItem>
<ComboBoxItem>Test3</ComboBoxItem>
</ComboBox>
</StackPanel>
</Window>
Code-behind
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
ToggleButton dropDownButton = GetFirstChildOfType<ToggleButton>(comboBox);
dropDownButton.IsEnabled = false;
}
public static T GetFirstChildOfType<T>(DependencyObject dependencyObject) where T : DependencyObject
{
if (dependencyObject == null)
{
return null;
}
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(dependencyObject); i++)
{
var child = VisualTreeHelper.GetChild(dependencyObject, i);
var result = (child as T) ?? GetFirstChildOfType<T>(child);
if (result != null)
{
return result;
}
}
return null;
}
}
Output
Notes
Always use GetFirstChildOfType() function only when the control will be fully loaded, otherwise it will not find it and give null. In this case, I put this code in the event Window_Loaded which says that all the controls of the Window successfully load.
Edit: another version
Not to say that this version is easier to implement, but it would be more correct and a bit easier to use.
So, we need a template for your ComboBox, because it allows access to elements that are within the control. Just like that, the ToggleButton can not be accessed from both the code and of XAML.
We create attached dependency property that will serve the current ComboBox another property, such as which will give access to our button Visibility.
Our property Visibility:
public static class ButtonExt
{
public static readonly DependencyProperty VisibilityProperty;
public static void SetVisibility(DependencyObject DepObject, Visibility value)
{
DepObject.SetValue(VisibilityProperty, value);
}
public static Visibility GetVisibility(DependencyObject DepObject)
{
return (Visibility)DepObject.GetValue(VisibilityProperty);
}
static ButtonExt()
{
PropertyMetadata VisibiltyPropertyMetadata = new PropertyMetadata(Visibility.Collapsed);
VisibilityProperty = DependencyProperty.RegisterAttached("Visibility",
typeof(Visibility),
typeof(ButtonExt),
VisibiltyPropertyMetadata);
}
}
Setter property in ComboBox template (skip version, full version see in project in App.xaml file):
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ComboBox}">
<Grid>
<ToggleButton Name="ToggleButton"
Template="{StaticResource ComboBoxToggleButton}"
IsChecked="{Binding Path=IsDropDownOpen,
Mode=TwoWay,
RelativeSource={RelativeSource TemplatedParent}}"
Visibility="{TemplateBinding PropertiesExtension:ButtonExt.Visibility}" // <------ Here
Grid.Column="2"
Focusable="False"
ClickMode="Press" />
Now, we are setting this property like this:
<ComboBox Name="comboBox"
Style="{StaticResource ComboBoxBaseStyle}"
PropertiesExtension:ButtonExt.Visibility="Visible"
Width="100"
Height="30"
SelectedIndex="0">
<ComboBoxItem>Test1</ComboBoxItem>
<ComboBoxItem>Test2</ComboBoxItem>
<ComboBoxItem>Test3</ComboBoxItem>
</ComboBox>
or in code-behind via Click event handlers:
private void HideButton_Click(object sender, RoutedEventArgs e)
{
ButtonExt.SetVisibility(comboBox, Visibility.Hidden);
}
private void ShowButton_Click(object sender, RoutedEventArgs e)
{
ButtonExt.SetVisibility(comboBox, Visibility.Visible);
}
Full version of example project is here.
Try with this
Dispatcher.BeginInvoke(new Action(() =>
{
ToggleButton dropDownButton = GetFirstChildOfType<ToggleButton>(cboMedicos);
if (dropDownButton != null)
{
dropDownButton.IsEnabled = false;
}
}), System.Windows.Threading.DispatcherPriority.Render);
public static T GetFirstChildOfType<T>(DependencyObject dependencyObject) where T : DependencyObject
{
if (dependencyObject == null)
{
return null;
}
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(dependencyObject); i++)
{
var child = VisualTreeHelper.GetChild(dependencyObject, i);
var result = (child as T) ?? GetFirstChildOfType<T>(child);
if (result != null)
{
return result;
}
}
return null;
}
So despite finding articles online I still cannot figure this out.
I have a Listbox
<ListBox HorizontalAlignment="Left" Margin="54,35,0,0" Name="resultsbox" VerticalAlignment="Top" Width="382" Visibility="Collapsed">
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding nameElement}"/>
</StackPanel>
</DataTemplate>
</ListBox>
That is databound to
ObservableCollection<string> results = new ObservableCollection<string>();
and is updated with
private void searchbox_TextChanged(object sender, TextChangedEventArgs e)
{
resultsbox.Visibility = Visibility.Visible;
resultsbox.ItemsSource = results;
if (results.Count == 0)
{
foreach (ele item in eles)
{
if (!results.Contains(item.nameElement))
{
results.Add(item.nameElement);
}
}
}
else
{
resultsbox.Items.Clear();
}
if (searchbox.Text.Equals(""))
{
window1.Height = 47;
resultsbox.Visibility = Visibility.Collapsed;
}
if (resultsbox.Items.Count == 0)
{
resultsbox.Visibility = Visibility.Collapsed;
window1.Height = 47;
}
else{
window1.Height = 47 + (22 * resultsbox.Items.Count);
}
}
It loads ALL the data in there but WILL NOT UPDATE!
If I do resultsbox.clear() it says you can't clear bound items. If you try and clear the source it does nothing. If you try and set the resultsbox itemsource to null and clear the source then rebind it, nothing. If you try and bind the listbox to an empty source it does nothing....
The answer was changing the foreach loop in the update from
resultsbox.ItemsSource = results;
if (results.Count == 0)
{
foreach (ele item in eles)
{
if (!results.Contains(item.nameElement))
{
results.Add(item.nameElement);
}
}
}
to
results.Clear();
foreach (ele item in eles)
{
if (item.nameElement.ToLower().Contains(searchbox.Text.ToLower()))
{
results.Add(item.nameElement);
}
}
resultsbox.ItemsSource = results;
You can try using Two-Way Mode Binding to achieve your requirement IMO,
<ListBox HorizontalAlignment="Left" Margin="54,35,0,0" Name="resultsbox" VerticalAlignment="Top" Width="382" Visibility="Collapsed">
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding nameElement, Mode=TwoWay}"/>
</StackPanel>
</DataTemplate>
i've defined an initial Table with three rows and 9 Column in Datagrid. right now button should be visible only if i select a row and then press another button that i defined in my Ribbon-Tab after that my Button will be Visible. sofar everything works well, but the Problem is after saving my Table, closing it and open the Table again the button is not there anymore. I set the Visibility based on if the DataGridCell.IsSelected, also a BooleanToVisibilityConverter to convert the boolean value to a Visibility one.
can anyone help!
XAML:
<DataGrid.Resources>
<BooleanToVisibilityConverter x:Key="BoolToVisConverter" />
</DataGrid.Resources>
<DataGridTemplateColumn x:Name="subgraphtyp" Header="H." Width="50">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Name="btnTable" Visibility="{Binding Path=Hinterlegung, Converter=
{StaticResource BoolToVisConverter}}" Height="20" Width="25"
Click="Button_Table_Click">
<Image Height="16" Source="Subgraph.png" Stretch="Fill" Width="16"/>
</Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
C#:
public bool Hinterlegung { get; set; }
private void Button_StartTableModus(object sender, RoutedEventArgs e)
{
if (DataGrid1.SelectedItem != null && tabItem1.IsSelected)
{
TableDataRowStringItem item = (TableDataRowStringItem)DataGrid1.CurrentItem;
string wert = item.ObjectType;
string rowName = item.Name;
if (wert == "Function" || wert == "Process")
{
item.Hinterlegung = true;
if (!tabControl.Items.Contains(tabItem2))
{
tabControl.Items.Add(tabItem2);
tabItem2.Focus();
tabItem2.IsSelected = true;
tabItem2.Header = rowName;
TableTab.Visibility = Visibility.Visible;
openTabs++;
DataGrid2.IsReadOnly = false;
starting_Table_Mod_at_start2V();
}
}
}
}
//this my initial Table
private ObservableCollection<TableDataRowStringItem> tableobject = new
ObservableCollection<TableDataRowStringItem>();
private void starting_Table_Mod_at_start2V()
{
List<TableDataRowStringItem> rowstringList = new List<TableDataRowStringItem>();
TableDataRowStringItem item = new TableDataRowStringItem();
item.RowNumber = 1; item.saveFlag = true; item.ObjectType = "E"; item.Name = "E";
item.PredecessorRowNumber = "0"; rowstringList.Add(item);
item = new TableDataRowStringItem();
item.RowNumber = 2; item.ObjectType = "Function"; item.Name = "Function";
item.PredecessorRowNumber = "1"; rowstringList.Add(item);
item = new TableDataRowStringItem();
item.RowNumber = 3; item.ObjectType = "E"; item.Name = "E";
item.PredecessorRowNumber = "2"; rowstringList.Add(item);
for (int i = 0; i < rowstringList.Count; i++)
{
tableobject.Add(rowstringList[i]);
}
DataGrid2.ItemsSource = tableobject;
}
Your button's visibility is bound to your Hinterlegung variable which has a default value of false. So as best as I can tell, you change it to true in this method - Button_StartTableModus. But, when you reinitialize, the value reverts to false, so you need to set it to true.