Search Results

Search found 365 results on 15 pages for 'selecteditem'.

Page 7/15 | < Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >

  • Trouble adding video controls to video selected by XML comboBox

    - by user560128
    Hello, it's been a few years since I've touched flash, so perhaps I'm just overlooking something. If anyone could look at the code and offer any suggestions that would be awesome. What's working, I select a video from a combobox that is populated from an XML file, pick the video and it plays. I've been trying to add pause/play, stop, forward and reverse functionality, once I get that to work I also want to add a video scrubber(slider), and previous/next buttons to go to the previous/next video as listed in the xml file. At the moment I have a component button on the stage called playButton, which I'm trying to use for pause/play functionality. Below is my code, the player control is at the very bottom. Thanks. import fl.data.DataProvider; var nc:NetConnection = new NetConnection(); nc.connect(null); var ns:NetStream = new NetStream(nc); var videosXML:XML = new XML(); var loader:URLLoader = new URLLoader(); var request:URLRequest= new URLRequest("xml/videos.xml"); var videos:Array = new Array({label:"Select a Video",data:""}); var client:Object = new Object(); theVideo.attachNetStream(ns); ns.client = client; loader.addEventListener(Event.COMPLETE,loaderOnComplete); loader.load (request); function loaderOnComplete(event:Event):void{ videosXML = new XML(event.target.data); for each (var video:XML in videosXML.video){ videos.push({label:video.name.toString(),data:video.url.toString()}); } moviesCB.dataProvider = new DataProvider(videos); } moviesCB.addEventListener(Event.CHANGE, changeHandler); function changeHandler(event:Event):void { if(ComboBox(event.target).selectedItem.data != ""){ ns.play(ComboBox(event.target).selectedItem.data); } }; client.onMetaData = metadataHandler; function metadataHandler(md:Object):void{ } //player controls playButton.onRelease = function() { ns.pause(); }

    Read the article

  • State Animation on ListBox ItemTemplate

    - by Peanut
    I have a listbox which reads from Observable collection, and is ItemTemplate'ed: <DataTemplate x:Key="DataTemplate1"> <Grid x:Name="grid" Height="47.333" Width="577" Opacity="0.495"> <Image HorizontalAlignment="Left" Margin="10.668,8,0,8" Width="34" Source="{Binding ImageLocation}"/> <TextBlock Margin="56,8,172.334,8" TextWrapping="Wrap" Text="{Binding ApplicationName}" FontSize="21.333"/> <Grid x:Name="grid1" HorizontalAlignment="Right" Margin="0,10.003,-0.009,11.33" Width="26" Opacity="0" RenderTransformOrigin="0.5,0.5"> <Image HorizontalAlignment="Stretch" Margin="0" Source="image/downloads.png" Stretch="Fill" MouseDown="Image_MouseDown" /> </Grid> </Grid> </DataTemplate> <ListBox x:Name="searchlist" Margin="8" ItemTemplate="{DynamicResource DataTemplate1}" ItemsSource="{Binding SearchResults}" SelectionChanged="searchlist_SelectionChanged" ItemContainerStyle="{DynamicResource ListBoxItemStyle1}" /> In general, my question is "What is the easiest way to do Animation on Particular Items in this listbox As they are selected? Basically the image inside the "grid1" will be setting its opacity to 1, slowly. I would prefer to use states, but I do not know of any way to just tell blend and xaml to "When a selected item is changed, change the image opacity to 1 over a period of .3 seconds". Infact, I have been doing this in the .cs file using the VisualStateManager. Also, there is another issue. When the selected index is changed, we goto the CS file and look at SelectedItem. SelectedItem returns an instance of the Object in which it was bound to (The object inside the observable collection), and NOT an instance of the DataTemplate/ListItem etc. So how am I able to pull the correct image out of this list? State animation with VisualStateManager I can handle fine if its just normal things, but when it comes to generated listboxes' items, I'm lost. Thanks

    Read the article

  • .NET ValidationRule problem

    - by PaN1C_Showt1Me
    Hi ! I have a control with this validation <MyPicker.SelectedItem> <Binding Path="Person.Value" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged" NotifyOnValidationError="True"> <Binding.ValidationRules> <rules:MyValidationRule ValidationType="notnull"/> </Binding.ValidationRules> </Binding> </MyPicker.SelectedItem> This is the Validation Class: class MyValidationRule : ValidationRule { private string _validationType; public string ValidationType { get { return _validationType; } set { _validationType = value; } } public override ValidationResult Validate(object value, CultureInfo cultureInfo) { ValidationResult trueResult = new ValidationResult(true, null); switch (_validationType.ToLower()) { case "notnull": return value == null ? new ValidationResult(false, "EMPTY FIELD") : trueResult; default: return trueResult; } } } Question: When the property is changed, then the Validate( ) method is called which is correct. But to call this method at the very beginning when the MyControl is created? I need to prove immediate after initialize if the there's a null value in the control (and display a validation error)

    Read the article

  • Text box loses focus when DIV is hovered

    - by Konoplianko
    Hello. I have a problem: When I enter a text into suggestion text box, popup panel appears. But when user places mouse over this popup panel with suggestions - text box loses focus. What should I do to prevent losing focus ? Example which have the same behaviour: http://demo.raibledesigns.com/gwt-autocomplete/ Thanks for any help. Update 1 SuggestionMenu which is being shown is extending MenuBar which sets focus for all menu items. void itemOver(MenuItem item, boolean focus) { if (item == null) { // Don't clear selection if the currently selected item's menu is showing. if ((selectedItem != null) && (shownChildMenu == selectedItem.getSubMenu())) { return; } } // Style the item selected when the mouse enters. selectItem(item); if (focus) { focus(); } // If child menus are being shown, or this menu is itself // a child menu, automatically show an item's child menu // when the mouse enters. if (item != null) { if ((shownChildMenu != null) || (parentMenu != null) || autoOpen) { doItemAction(item, false); } } } It's clear that i cant fix loosing focus. Now question is - how to make on pressing backspace or any key to focus on edit box? Thanks in advance

    Read the article

  • How do I link one listview to another to create a football league table?

    - by Richard Nixon
    Hi I am creating a football system in windows forms c#. I have one listview where data is entered. I have 4 columns, 2 with team names linked to combo boxes and 2 with the scores linked to numericupdown controls. There are 3 buttons to add the results, Remove and clear. the code is below: private void addButton_Click(object sender, EventArgs e) { { ListViewItem item = new ListViewItem(comboBox1.SelectedItem.ToString()); item.SubItems.Add(numericUpDown1.Value.ToString()); item.SubItems.Add(numericUpDown2.Value.ToString()); item.SubItems.Add(comboBox2.SelectedItem.ToString()); listView1.Items.Add(item); } } private void clearButton_Click(object sender, EventArgs e) { listView1.Items.Clear(); } private void removeButton_Click(object sender, EventArgs e) { foreach (ListViewItem itemSelected in listView1.SelectedItems) { listView1.Items.Remove(itemSelected); } } I have another listview that i want to link the first one to. The second one is a usual english football league table and i want to use maths to add up the games played and the points etc. please help. cheers

    Read the article

  • How to Access value of dynamically created control?

    - by sharad
    i have asp.net web application in which i need to create form dynamically depend upon table which user selected.however,i created form dynamically with it's control like text box,drop downlist etc. but not able to access those controls at particular button click event. My form scenario is like this: i have dropdownlist in which i display list of tables,button control say display( on click event which i redirect page with some addition in querystring so that at page init it dynamically genrate controls) and another button control which used to access this controls value say Submit and store in database. This is my code: At Display button Click event: Response.Redirect("dynamic_main.aspx?mode=edit&tablename=" + CMBTableList.SelectedItem.ToString()); This is code For page.Init level if (Request.QueryString["mode"] != null) { if (Request.QueryString["mode"].ToString() == "edit") { Session["tablename"] = Request.QueryString["tablename"].ToString(); // if (Session["tablename"].ToString() == CMBTableList.SelectedItem.ToString()) //{ createcontrol(Session["tablename"].ToString()); // } } } i have used createcontrol() which genrate controls Code For Submit Button: string[] contid=controlid.Value.Split(','); MasterPage ctl00 = FindControl("ctl00") as MasterPage; ContentPlaceHolder cplacehld = ctl00.FindControl("ContentPlaceHolder2") as ContentPlaceHolder; Panel panel1 = cplacehld.FindControl("plnall") as Panel; Table tabl1 = panel1.FindControl("id1") as Table; foreach (string sin in contid) { string splitcvalu = sin.Split('_')[0].ToString(); ControlsAccess contaccess = new ControlsAccess(); if (splitcvalu.ToString() == "txt") { TextBox txt = (TextBox)tabl1.FindControl(sin.ToString()); //TextBox txt = cplacehld.FindControl(sin.ToString()) as TextBox; val = txt.ID; } else { DropDownList DDL = cplacehld.FindControl(sin.ToString()) as DropDownList; } } Here i am no able to access this textbox or drop downlist.i am getting id of particular control from hidden field controlid in which i have stored it during genrating controls. i have used findcontrol() it works in case of finding masterpage,contentplaceholder,table etc. but in case of textbox or other control it doesnt work it shows it returns null. Anyone can help me. Thanks

    Read the article

  • WPF: How to bind and update display with DataContext

    - by Am
    I'm trying to do the following thing: I have a TabControl with several tabs. Each TabControlItem.Content points to PersonDetails which is a UserControl Each BookDetails has a dependency property called IsEditMode I want a control outside of the TabControl , named ToggleEditButton, to be updated whenever the selected tab changes. I thought I could do this by changing the ToggleEditButton data context, by it doesn't seem to work (but I'm new to WPF so I might way off) The code changing the data context: private void tabControl1_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (e.Source is TabControl) { if (e.Source.Equals(tabControl1)) { if (tabControl1.SelectedItem is CloseableTabItem) { var tabItem = tabControl1.SelectedItem as CloseableTabItem; RibbonBook.DataContext = tabItem.Content as BookDetails; ribbonBar.SelectedTabItem = RibbonBook; } } } } The DependencyProperty under BookDetails: public static readonly DependencyProperty IsEditModeProperty = DependencyProperty.Register("IsEditMode", typeof (bool), typeof (BookDetails), new PropertyMetadata(true)); public bool IsEditMode { get { return (bool)GetValue(IsEditModeProperty); } set { SetValue(IsEditModeProperty, value); SetValue(IsViewModeProperty, !value); } } And the relevant XAML: <odc:RibbonTabItem Title="Book" Name="RibbonBook"> <odc:RibbonGroup Title="Details" Image="img/books2.png" IsDialogLauncherVisible="False"> <odc:RibbonToggleButton Content="Edit" Name="ToggleEditButton" odc:RibbonBar.MinSize="Medium" SmallImage="img/edit_16x16.png" LargeImage="img/edit_32x32.png" Click="Book_EditDetails" IsChecked="{Binding Path=IsEditMode, Mode=TwoWay}"/> ... There are two things I want to accomplish, Having the button reflect the IsEditMode for the visible tab, and have the button change the property value with no code behind (if posible) Any help would be greatly appriciated.

    Read the article

  • Bug with DataBinding in WPF Host in Winforms?

    - by Tigraine
    Hi Guys, I've spent far too much time with this and can't find the mistake. Maybe I'm missing something very obvious or I may have just found a bug in the WPF Element Host for Winforms. I am binding a ListView to a ObeservableList that lives on my ProductListViewModel. I'm trying to implement searching for the ListView with the general Idea to just change the ObservableList with a new list that is filtered. Anyway, the ListView Binding code looks like this: <ListView ItemsSource="{Binding Path=Products}" SelectedItem="{Binding Path=SelectedItem}" SelectionMode="Single"> <ListView.ItemContainerStyle> <Style TargetType="{x:Type ListViewItem}"> <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}"></Setter> </Style> </ListView.ItemContainerStyle> <ListView.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding Name}"></TextBlock> </DataTemplate> </ListView.ItemTemplate> </ListView> And the ViewModel code is as vanilla as it can get: private ObservableCollection<ProductViewModel> products; public ObservableCollection<ProductViewModel> Products { get { return products; } private set { if (products != value) { products = value; OnPropertyChanged("Products"); } } } Now the problem here: Once I debug into my OnPropertyChanged method, I can see that there are no subscribers to the PropertyChanged event (it's null), so nothing happens on the UI.. I already tried Mode=TwoWay and other Binding modes, it seems I can't get the ListView to subscribe to the ItemsSource... Can anyone help me with this? I'm just about to forget about the ElemenHost and just do it in Winforms greetings Daniel

    Read the article

  • Binding not working correctly in silverlight

    - by Harsh Maurya
    I am using a DataGrid in my silverlight project which contains a custom checkbox column. I have binded its command property with a property of my ViewModel class. Now, the problem is that I want to send the "selected item" of DataGrid through the command paramter for which I have written the following code : <sdk:DataGrid AutoGenerateColumns="False" Margin="10,0,10,0" Name="dataGridOrders" ItemsSource="{Binding OrderList}" Height="190"> <sdk:DataGrid.Columns> <sdk:DataGridTemplateColumn Header="Select"> <sdk:DataGridTemplateColumn.CellTemplate> <DataTemplate> <CheckBox> <is:Interaction.Triggers> <is:EventTrigger EventName="Checked"> <is:InvokeCommandAction Command="{Binding Source={StaticResource ExecutionTraderHomePageVM},Path=OrderSelectedCommand,Mode=TwoWay}" CommandParameter="{Binding ElementName=dataGridOrders,Path=SelectedItem}" /> </is:EventTrigger> <is:EventTrigger EventName="Unchecked"> <is:InvokeCommandAction Command="{Binding Source={StaticResource ExecutionTraderHomePageVM},Path=OrderSelectedCommand,Mode=TwoWay}" CommandParameter="{Binding ElementName=dataGridOrders,Path=SelectedItem}" /> </is:EventTrigger> </is:Interaction.Triggers> </CheckBox> But I am always getting null in the parameter of my command's execute method. I have tried with other properties of DataGrid such as Width, ActualHeight e.t.c. but of no use. What am I missing here ?

    Read the article

  • Problem in DataBinding an Enum using dictionary approach to a combobox in WPF.

    - by Ashish Ashu
    I have a Dictionary which is binded to a combobox. I have used dictionary to provide spaces in enum. public enum Option {Enter_Value, Select_Value}; Dictionary<Option,string> Options; <ComboBox x:Name="optionComboBox" SelectionChanged="optionComboBox_SelectionChanged" SelectedValuePath="Key" DisplayMemberPath="Value" SelectedItem="{Binding Path = SelectedOption}" ItemsSource="{Binding Path = Options}" /> This works fine. My queries: 1. I am not able to set the initial value to a combo box. In above XAML snippet the line SelectedItem="{Binding Path = SelectedOption}" is not working. I have declared SelectOption in my viewmodel. This is of type string and I have intialized this string value in my view model as below: SelectedOption = Options[Options.Enter_Value].ToString(); 2. The combobox is binded to datadictionary which have two options first is "Enter_value" and second is "Select_value" which is actually Option enum. Based on the Option enum value I want to perform different action. For example if option is equal to option.Enter_value then Combo box becomes editable and user can enter the numeric value in it. if option is equal to option.Select_value value then the value comes from the database and the combo box becomes read only and shows the fetched value from the database. Please Help!!

    Read the article

  • lambda expressions in VB.NET... what am I doing wrong???

    - by Bob
    when I run this C# code, no problems... but when I translate it into VB.NET it compiles but blows due to 'CompareString' member not being allowed in the expression... I feel like I'm missing something key here... private void PrintButton_Click(object sender, EventArgs e) { if (ListsListBox.SelectedIndex > -1) { //Context using (ClientOM.ClientContext ctx = new ClientOM.ClientContext(UrlTextBox.Text)) { //Get selected list string listTitle = ListsListBox.SelectedItem.ToString(); ClientOM.Web site = ctx.Web; ctx.Load(site, s => s.Lists.Where(l => l.Title == listTitle)); ctx.ExecuteQuery(); ClientOM.List list = site.Lists[0]; //Get fields for this list ctx.Load(list, l => l.Fields.Where(f => f.Hidden == false && (f.CanBeDeleted == true || f.InternalName == "Title"))); ctx.ExecuteQuery(); //Get items for the list ClientOM.ListItemCollection listItems = list.GetItems( ClientOM.CamlQuery.CreateAllItemsQuery()); ctx.Load(listItems); ctx.ExecuteQuery(); // DOCUMENT CREATION CODE GOES HERE } MessageBox.Show("Document Created!"); } } but in VB.NET code this errors due to not being allowed 'CompareString' members in the ctx.Load() methods... Private Sub PrintButton_Click(sender As Object, e As EventArgs) If ListsListBox.SelectedIndex > -1 Then 'Context Using ctx As New ClientOM.ClientContext(UrlTextBox.Text) 'Get selected list Dim listTitle As String = ListsListBox.SelectedItem.ToString() Dim site As ClientOM.Web = ctx.Web ctx.Load(site, Function(s) s.Lists.Where(Function(l) l.Title = listTitle)) ctx.ExecuteQuery() Dim list As ClientOM.List = site.Lists(0) 'Get fields for this list ctx.Load(list, Function(l) l.Fields.Where(Function(f) f.Hidden = False AndAlso (f.CanBeDeleted = True OrElse f.InternalName = "Title"))) ctx.ExecuteQuery() 'Get items for the list Dim listItems As ClientOM.ListItemCollection = list.GetItems(ClientOM.CamlQuery.CreateAllItemsQuery()) ctx.Load(listItems) ' DOCUMENT CREATION CODE GOES HERE ctx.ExecuteQuery() End Using MessageBox.Show("Document Created!") End If End Sub

    Read the article

  • WPF Single Selection Across Multiple ItemsControls

    - by gregsdennis
    Part of my app has a month-view calendar interface, but I'm having trouble with item selection. The interface is set up so that each of the days in the view contains a ListBox of items, much like the month view in Outlook. The problem I'm experiencing is that I need to maintain a single item selection across all of the ListBoxes. Below is a sample window that should adequately describe my situation. I need to maintain a single selection between both ListBoxes. <Window x:Class="StackOverflow.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> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition /> </Grid.ColumnDefinitions> <ListBox ItemsSource="{Binding Numbers}" SelectedItem="{Binding SelectedObject"/> <ListBox Grid.Column="1" ItemsSource="{Binding Dates}" SelectedItem="{Binding SelectedObject"/> </Grid> </Window> In this primitive example, I would expect that when the SelectedObject property of my view model gets set to an item that's not in one ListBox, the selection would be removed in that ListBox, but that doesn't happen. I understand that I can simply name each ListBox, and hook into the SelectionChanged event. I'd prefer to not have to do that with an entire month-view calendar. There has to be a better way. In a previous iteration of the app, I was able to create a SelectionManager static class with an attached property that was used to maintain selection. However, I can't use this now as the classes I'm using for my items are not DependencyObjects, and I'd really prefer not to have to create DependencyObject wrapper classes as this will considerably complicate my architecture. Thanks.

    Read the article

  • Storing values in the DataValueField and DataTextField of a dropdownlist using a linq query

    - by user1318369
    I have a website for dance academy where Users can register and add/drop dance classes. In the web page to drop a particular dance, for a particular user, the dropdown displays her registered dances. Now I want to delete one of the dances from the list. So I'll remove the row from the table and also from the dropdownlist. The problem is that everytime the item with the lowest ID (index) is getting deleted, no matter which one the user selects. I think I am storing the DataTextField and DataValueField for the dropdown incorrectly. The code is: private void PopulateDanceDropDown() { // Retrieve the username MembershipUser currentUser = Membership.GetUser(); var username = currentUser.UserName; // Retrive the userid of the curren user var dancerIdFromDB = from d in context.DANCER where d.UserName == username select d.UserId; Guid dancerId = new Guid(); var first = dancerIdFromDB.FirstOrDefault(); if (first != null) { dancerId = first; } dances.DataSource = (from dd in context.DANCER_AND_DANCE where dd.UserId == dancerId select new { Text = dd.DanceName, Value = dd.DanceId }).ToList(); dances.DataTextField = "Text"; dances.DataValueField = "Value"; dances.DataBind(); } protected void dropthedance(object o, EventArgs e) { String strDataValueField = dances.SelectedItem.Value; int danceIDFromDropDown = Convert.ToInt32(strDataValueField); var dancer_dance = from dd in context.DANCER_AND_DANCE where dd.DanceId == danceIDFromDropDown select dd; foreach (var dndd in dancer_dance) { context.DANCER_AND_DANCE.DeleteOnSubmit(dndd); } try { context.SubmitChanges(); } catch (Exception ex) { Console.WriteLine(ex); } } The problem is in the line: String strDataValueField = dances.SelectedItem.Value; The strDataValueField is always getting the minimum id from the list of dance item ids in the dropdown (which happens by default). I want this to hold the id of the dance selected by the user.

    Read the article

  • How to delay execution of a method in c#?

    - by Pandiya Chendur
    I have this if condition, if (sendSMS(Convert.ToInt32(DLComportNo.SelectedItem.Text), TxtDriMob.Text, TxtCliDet.Text) && sendSMS(Convert.ToInt32(DLComportNo.SelectedItem.Text), TxtCliMob.Text, TxtDriDet.Text)) { // I am inserting details to my db } and my sendSMS method looks like this, private bool sendSMS(int portNo, string mobNo, string details) { try { SerialPort SerialPort1 = new SerialPort(); SerialPort1.PortName = "COM" + portNo.ToString(); SerialPort1.BaudRate = 9600; SerialPort1.Parity = Parity.None; SerialPort1.DataBits = 8; SerialPort1.StopBits = StopBits.One; SerialPort1.RtsEnable = true; SerialPort1.DtrEnable = true; SerialPort1.Encoding.GetEncoder(); SerialPort1.ReceivedBytesThreshold = 1; SerialPort1.NewLine = Environment.NewLine; SerialPort1.Open(); SerialPort1.Write("AT" + SerialPort1.NewLine); Sleep(500); SerialPort1.Write("AT+CMGF=1" + SerialPort1.NewLine); Sleep(500); SerialPort1.Write("AT+CMGS=" + (char)34 + mobNo + (char)34 + SerialPort1.NewLine); Sleep(1000); SerialPort1.Write(details + (char)26); Sleep(2000); SerialPort1.Close(); } catch { } return true; } What happens is when i use break point in my sendSMS i get my output (ie) both the methods get executed and messages are sent properly... But when i removed my breakpoint both the methods in the if statement are executed but message from the first method is sent and not from the second method.... Any suggestion?

    Read the article

  • WPF ComboBox Binding to non string object

    - by Mike L
    I'm using MVVM (MVVM Light Toolkit) and have a property on the view model which exposes a list of objects. The objects contain two properties, both strings, which correlate to an abbreviation and a description. I want the ComboBox to expose the pairing as "abbreviation - description". If I use a data template, it does this easily. I have another property on the view model which represents the object that should display as selected -- the chosen item in the ComboBox. I'm binding the ItemsSource to the list, as it represents the universe of available selections, and am trying to bind the SelectedItem to this object. I'm killing myself trying to figure out why I can't get it to work, and feeling more like a fraud by the hour. In trying to learn why this works, I created the same approach with just a list of strings, and a selected string. This works perfectly. So, it clearly has something to do with the typing... perhaps something in choosing equality? Or perhaps it has to do with the data template? Here is the XAML: <Window x:Class="MvvmLight1.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" DataContext="{Binding Main, Source={StaticResource Locator}}"> <Window.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="Skins/MainSkin.xaml" /> </ResourceDictionary.MergedDictionaries> <DataTemplate x:Key="DataTemplate1"> <StackPanel Orientation="Horizontal"> <TextBlock TextWrapping="Wrap" Text="{Binding CourtCode}"/> <TextBlock TextWrapping="Wrap" Text=" - "/> <TextBlock TextWrapping="Wrap" Text="{Binding CourtDescription}"/> </StackPanel> </DataTemplate> </ResourceDictionary> </Window.Resources> <Grid x:Name="LayoutRoot"> <ComboBox x:Name="cmbAbbrevDescriptions" Height="35" Margin="25,75,25,25" VerticalAlignment="Top" ItemsSource="{Binding Codes}" ItemTemplate="{DynamicResource DataTemplate1}" SelectedItem="{Binding selectedCode}" /> <ComboBox x:Name="cmbStrings" Height="35" Margin="25" VerticalAlignment="Top" ItemsSource="{Binding strs}" SelectedItem="{Binding selectedStr}"/> </Grid> </Window> And, if helpful, here is the ViewModel: using GalaSoft.MvvmLight; using MvvmLight1.Model; using System.Collections.Generic; namespace MvvmLight1.ViewModel { public class MainViewModel : ViewModelBase { public const string CodesPropertyName = "Codes"; private List<Court> _codes = null; public List<Court> Codes { get { return _codes; } set { if (_codes == value) { return; } var oldValue = _codes; _codes = value; // Update bindings and broadcast change using GalaSoft.Utility.Messenging RaisePropertyChanged(CodesPropertyName, oldValue, value, true); } } public const string selectedCodePropertyName = "selectedCode"; private Court _selectedCode = null; public Court selectedCode { get { return _selectedCode; } set { if (_selectedCode == value) { return; } var oldValue = _selectedCode; _selectedCode = value; // Update bindings and broadcast change using GalaSoft.Utility.Messenging RaisePropertyChanged(selectedCodePropertyName, oldValue, value, true); } } public const string strsPropertyName = "strs"; private List<string> _strs = null; public List<string> strs { get { return _strs; } set { if (_strs == value) { return; } var oldValue = _strs; _strs = value; // Update bindings and broadcast change using GalaSoft.Utility.Messenging RaisePropertyChanged(strsPropertyName, oldValue, value, true); } } public const string selectedStrPropertyName = "selectedStr"; private string _selectedStr = ""; public string selectedStr { get { return _selectedStr; } set { if (_selectedStr == value) { return; } var oldValue = _selectedStr; _selectedStr = value; // Update bindings and broadcast change using GalaSoft.Utility.Messenging RaisePropertyChanged(selectedStrPropertyName, oldValue, value, true); } } /// <summary> /// Initializes a new instance of the MainViewModel class. /// </summary> public MainViewModel() { Codes = new List<Court>(); Court code1 = new Court(); code1.CourtCode = "ABC"; code1.CourtDescription = "A Court"; Court code2 = new Court(); code2.CourtCode = "DEF"; code2.CourtDescription = "Second Court"; Codes.Add(code1); Codes.Add(code2); Court code3 = new Court(); code3.CourtCode = "DEF"; code3.CourtDescription = "Second Court"; selectedCode = code3; selectedStr = "Hello"; strs = new List<string>(); strs.Add("Goodbye"); strs.Add("Hello"); strs.Add("Ciao"); } } } And here is the ridiculously trivial class that is being exposed: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MvvmLight1.Model { public class Court { public string CourtCode { get; set; } public string CourtDescription { get; set; } } } Thanks!

    Read the article

  • How to set focus for CustCombBox in a CellEditingTemplate when entering page at the first time(MVVM

    - by Shamin
    PreparingCellForEdit="dg_PreparingCellForEdit" BeginningEdit="dg_BeginningEdit" <data:DataGridTemplateColumn MinWidth="300"> <data:DataGridTemplateColumn.HeaderStyle> <Style TargetType="primitives:DataGridColumnHeader" BasedOn="{StaticResource FOTDataGridColumnHeaderStyle}"> <Setter Property="ContentTemplate"> <Setter.Value> <DataTemplate> <TextBlock Text="{Binding CancelReasonText2,Source={StaticResource LabelResource}}" Style="{StaticResource TextBlockLabelStandardStyle}"/> </DataTemplate> </Setter.Value> </Setter> </Style> </data:DataGridTemplateColumn.HeaderStyle> <data:DataGridTemplateColumn.CellTemplate> <DataTemplate> <TextBlock Text="{Binding CancelReason.CancelCodeDescription}" Style="{StaticResource TextBlockLabelStandardStyle}"/> </DataTemplate> </data:DataGridTemplateColumn.CellTemplate> <data:DataGridTemplateColumn.CellEditingTemplate> <DataTemplate> <input:AutoCompleteBox x:Name="cBoxCancelReason" FilterMode="StartsWith" IsDropDownOpen="True" SelectedItem="{Binding CancelReason, Mode=TwoWay}" ItemsSource="{Binding CancelCodes}" ValueMemberPath="CancelCodeDescription" > <input:AutoCompleteBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding CancelCodeDescription}" Style="{StaticResource TextBlockLabelStandardStyle}"/> </DataTemplate> </input:AutoCompleteBox.ItemTemplate> </input:AutoCompleteBox> </DataTemplate> </data:DataGridTemplateColumn.CellEditingTemplate> </data:DataGridTemplateColumn> </data:DataGrid.Columns> </data:DataGrid> ---CodeBind public partial class CancelFlightView : UserControl,ICancelFlightView { private data.CancelCode DefaultCancelCode { get { data.CancelCode code = new data.CancelCode(); code.CancelCd = "-1"; code.CancelCodeDescription = "-- Select Cancel Reason --"; return code; } } public CancelFlightView() { InitializeComponent(); this.dg.LoadingRow += new EventHandler<DataGridRowEventArgs>(dg_LoadingRow); //this.Loaded += new RoutedEventHandler(CancelFlightView_Loaded); } void dg_LoadingRow(object sender, DataGridRowEventArgs e) { CheckBox checkBox = (CheckBox)dg.Columns[0].GetCellContent(e.Row); if (checkBox.IsChecked.Value) { FrameworkElement obj = (FrameworkElement)dg.Columns[1].GetCellContent(e.Row); System.Windows.Browser.HtmlPage.Plugin.Focus(); DataGridCell cellEdit = (DataGridCell)obj.Parent; cellEdit.Focus(); dg.BeginEdit(); } } //private void UserControl_Loaded(object sender, RoutedEventArgs e) //{ // if (DataContext != null) // { // CancelFlightViewModel viewModel = (CancelFlightViewModel)DataContext; // viewModel.View = this; // viewModel.Grid = dg; // //viewModel.InitFocus(); // } //} //void CancelFlightView_Loaded(object sender, RoutedEventArgs e) //{ // if (dg.SelectedItem != null) // { // CheckBox checkBox = (CheckBox)dg.Columns[0].GetCellContent(dg.SelectedItem); // if (checkBox.IsChecked.Value) // { // DataGridCell cellEdit = ((DataGridCell)((System.Windows.Controls.Primitives.DataGridCellsPresenter)((DataGridCell)checkBox.Parent).Parent).Children[1]); // dg.CurrentColumn = dg.Columns[1]; // System.Windows.Browser.HtmlPage.Plugin.Focus(); // cellEdit.Focus(); // dg.BeginEdit(); // } // } //} public CancelFlightView(CancelFlightViewModel viewModel):this() { ViewModel = viewModel; } private void dg_PreparingCellForEdit(object sender, DataGridPreparingCellForEditEventArgs e) { object obj = dg.Columns[1].GetCellContent(e.Row); if (obj != null && obj.GetType() == typeof(AutoCompleteBox)) { AutoCompleteBox cBoxCancelReason = (AutoCompleteBox)obj; System.Windows.Browser.HtmlPage.Plugin.Focus(); cBoxCancelReason.Focus(); } } private void CustomComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { } private void dg_BeginningEdit(object sender, DataGridBeginningEditEventArgs e) { } private void chkFlight_Click(object sender, RoutedEventArgs e) { CheckBox chkTemp = sender as CheckBox; if (!chkTemp.IsChecked.Value) { } else { DataGridCell cellEdit = ((DataGridCell)((System.Windows.Controls.Primitives.DataGridCellsPresenter)((DataGridCell)chkTemp.Parent).Parent).Children[1]); dg.CurrentColumn = dg.Columns[1]; cellEdit.Focus(); dg.BeginEdit(); } } private void LayoutRoot_KeyUp(object sender, KeyEventArgs e) { //if (e.Key == Key.Enter) //{ //} } #region ICancelFlightView Members public CancelFlightViewModel ViewModel { get { return DataContext as CancelFlightViewModel; } set { DataContext = value; } } #endregion } Now, when user click CheckBox, I can set focus on CustCombBox, but I can't set focus on Whose checkBox.IsChecked.Value = true when page is opened for the first time. is it possible on MVVM pattern? Looking forward your reply, thanks very much.

    Read the article

  • treeview binding wpf cannot bind nested property in a class

    - by devnet247
    Hi all New to wpf and therefore struggling a bit. I am putting together a quick demo before we go for the full implementation I have a treeview on the left with Continent Country City structure when a user select the city it should populate some textboxes in a tabcontrol on the right hand side I made it sort of work but cannot make it work with composite objects. In a nutshell can you spot what is wrong with my zaml or code. Why is not binding to a my CityDetails.ClubsCount or CityDetails.PubsCount? What I am building is based on http://www.codeproject.com/KB/WPF/TreeViewWithViewModel.aspx Thanks a lot for any suggestions or reply DataModel public class City { public City(string cityName) { CityName = cityName; } public string CityName { get; set; } public string Population { get; set; } public string Area { get; set; } public CityDetails CityDetailsInfo { get; set; } } public class CityDetails { public CityDetails(int pubsCount,int clubsCount) { PubsCount = pubsCount; ClubsCount = clubsCount; } public int ClubsCount { get; set; } public int PubsCount { get; set; } } ViewModel public class CityViewModel : TreeViewItemViewModel { private City _city; private RelayCommand _testCommand; public CityViewModel(City city, CountryViewModel countryViewModel):base(countryViewModel,false) { _city = city; } public string CityName { get { return _city.CityName; } } public string Area { get { return _city.Area; } } public string Population { get { return _city.Population; } } public City City { get { return _city; } set { _city = value; } } public CityDetails CityDetailsInfo { get { return _city.CityDetailsInfo; } set { _city.CityDetailsInfo = value; } } } XAML <DockPanel> <DockPanel LastChildFill="True"> <Label DockPanel.Dock="top" Content="Title " HorizontalAlignment="Center"></Label> <StatusBar DockPanel.Dock="Bottom"> <StatusBarItem Content="Status Bar" ></StatusBarItem> </StatusBar> <Grid DockPanel.Dock="Top"> <Grid.ColumnDefinitions> <ColumnDefinition/> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="2*"/> </Grid.ColumnDefinitions> <TreeView Name="tree" ItemsSource="{Binding Continents}"> <TreeView.ItemContainerStyle> <Style TargetType="{x:Type TreeViewItem}"> <Setter Property="IsExpanded" Value="{Binding IsExpanded,Mode=TwoWay}"/> <Setter Property="IsSelected" Value="{Binding IsSelected,Mode=TwoWay}"/> <Setter Property="FontWeight" Value="Normal"/> <Style.Triggers> <Trigger Property="IsSelected" Value="True"> <Setter Property="FontWeight" Value="Bold"></Setter> </Trigger> </Style.Triggers> </Style> </TreeView.ItemContainerStyle> <TreeView.Resources> <HierarchicalDataTemplate DataType="{x:Type ViewModels:ContinentViewModel}" ItemsSource="{Binding Children}"> <StackPanel Orientation="Horizontal"> <Image Width="16" Height="16" Margin="3,0" Source="Images\Continent.png"/> <TextBlock Text="{Binding ContinentName}"/> </StackPanel> </HierarchicalDataTemplate> <HierarchicalDataTemplate DataType="{x:Type ViewModels:CountryViewModel}" ItemsSource="{Binding Children}"> <StackPanel Orientation="Horizontal"> <Image Width="16" Height="16" Margin="3,0" Source="Images\Country.png"/> <TextBlock Text="{Binding CountryName}"/> </StackPanel> </HierarchicalDataTemplate> <DataTemplate DataType="{x:Type ViewModels:CityViewModel}" > <StackPanel Orientation="Horizontal"> <Image Width="16" Height="16" Margin="3,0" Source="Images\City.png"/> <TextBlock Text="{Binding CityName}"/> </StackPanel> </DataTemplate> </TreeView.Resources> </TreeView> <GridSplitter Grid.Row="0" Grid.Column="1" Background="LightGray" Width="5" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/> <Grid Grid.Column="2" Margin="5" > <TabControl> <TabItem Header="Details" DataContext="{Binding Path=SelectedItem.City, ElementName=tree, Mode=OneWay}"> <StackPanel > <TextBlock VerticalAlignment="Center" FontSize="12" Text="{Binding CityName}"/> <TextBlock VerticalAlignment="Center" FontSize="12" Text="{Binding Area}"/> <TextBlock VerticalAlignment="Center" FontSize="12" Text="{Binding Population}"/> <!-- DONT WORK WHY--> <TextBlock VerticalAlignment="Center" FontSize="12" Text="{Binding SelectedItem.CityDetailsInfo.ClubsCount}"/> <TextBlock VerticalAlignment="Center" FontSize="12" Text="{Binding SelectedItem.CityDetailsInfo.PubsCount}"/> </StackPanel> </TabItem> </TabControl> </Grid> </Grid> </DockPanel> </DockPanel>

    Read the article

  • How to name an subclass that add a minor, detailed thing?

    - by Louis Rhys
    What is the most concise (yet descriptive) way of naming a subclass that only add a specific minor thing to the parent? I encountered this case a lot in WPF, where sometime I have to add a small functionality to an out-of-the-box control for specific cases. Example: TreeView doesn't change the SelectedItem on right-click, but I have to make one that does in my application. Some possible names are TreeViewThatChangesSelectedItemOnRightClick (way too wordy and maybe difficult to read because there is so many words concantenated together) TreeView_SelectedItemChangesOnRightClick (slightly more readable, but still too wordy and the underscore also breaks the normal convention for class names) TreeViewThatChangesSIOnRC (non-obvious acronym), ExtendedTreeView (more concise, but doesn't describe what it is doing. Besides, I already found a class called this in the library, that I don't want to use/modify in my application). LouisTreeView, MyTreeView, etc. (doesn't describe what it is doing). It seems that I can't find a name which sounds right. What do you do in situation like this?

    Read the article

  • [Silverlight] How to choose the webcam resolution

    - by Benjamin Roux
    Hello, Today I’m gonna show you how to choose the webcam resolution when using Silverlight. By default most of them are in 640x480 which can be sometimes insufficient. VideoCaptureDevice source = devices.SelectedItem as VideoCaptureDevice; source.DesiredFormat = new VideoFormat(PixelFormatType.Unknown, 4096, 4096, 30); The magic thing with this line, is that the camera will choose the best resolution available (and not absolutely 4096x4096). You can also get all the supported formats using the SupportedFormats property. Hope this help.

    Read the article

  • MVVM pattern and nested view models - communication and lookup lists

    - by LostInWPF
    I am using Prism for a new application that I am creating. There are several lookup lists that will be used in several places in the application. Therefore it makes sense to define it once and use that everywhere I need that functionality. My current solution is to use typed data templates to render the controls inside a content control. <DataTemplate DataType={x:Type ListOfCountriesViewModel}> <ComboBox ItemsSource={Binding Countries} SelectedItem="{Binding SelectedCountry"/> </DataTemplate> <DataTemplate DataType={x:Type ListOfRegionsViewModel}> <ComboBox ItemsSource={Binding Countries} SelectedItem={Binding SelectedRegion} /> </DataTemplate> public class ParentViewModel { SelectedCountry get; set; SelectedRegion get; set; ListOfCountriesViewModel CountriesVM; ListOfRegionsViewModel RgnsVM; } Then in my window I have 2 content controls and the rest of the controls <ContentControl Content="{Binding CountriesVM}"></ContentControl> <ContentControl Content="{Binding RgnsVM}"></ContentControl> <Rest of controls on view> At the moment I have this working and the SelectedItems for the combo boxes are publising events via EventAggregator from the child view models which are then subscribed to in the parent view model. I am not sure that this is the best way to go as I can imagine I would end up with a lot of events very quickly and it will become unwieldy. Also if I was to use the same view model on another window it will publish the event and this parent viewmodel is subscribed to it which could have unintended consequences. My questions are :- Is this the best way to put lookup lists in a view which can be re-used across screens? How do I make it so that the combobox which is bound to the child viewmodel sets the relevant property on the parent viewmodel without using events / mediator. e.g in this case SelectedCountry for example? Any alternative implementation proposals for what I am trying to do? I have a feeling I am missing something obvious and there is so much info it is hard to know what is right so any help would be most gratefully received.

    Read the article

  • WPF ListView Cannot Trigger Selection Changed when only one row

    - by Traci
    I have a listview which has its datasource changed after update of a search textbox. When I enter search criteria that only returns one row, I am unable to trigger the OnSelectionChanged event The listbox works as expected at any other time. I have tried changing SelectedItem and SelectedIndex in Code, Clicking aimlessly on the ListView both on and off the row and are at the brink of insanity. Does anyone know of a solution so that I am able to change the selected item!! Help Please

    Read the article

  • combobox value string to int

    - by asli
    Hi,I have a question about converting types each other.I want to change the selected combobox value string to int but I get errors my code: int.Parse(age.SelectedItem.ToString()); What can I do for this problem?Thank you

    Read the article

  • DataTable DataRow Select String with Quotation Marks

    - by RBrattas
    Hi, My string include quotation mark; the select statement crash. vm_TEXT_string = "Hello 'French' People"; vm_DataTable_SELECT_string = "[MyField] = '" + vm_TEXT_string + "'"; DataRow[] o_DataRow_ARRAY_Found = vco_DataTable.Select (vm_DataTable_SELECT_string); I cannot use this statement: string filter = "[MyColumn]" + " LIKE '%" + SearchWord + "%'"; I found string format: DataRow[] oDataRow = oDataSet.Tables["HasDiseas"].Select ( string.Format ( "DName='{0}'", DiseasListBox.SelectedItem.ToString () ) ); Any suggestion to selecta string with quotation mark? Thank you, Rune

    Read the article

  • casing the object values

    - by deep
    Hai am using telerik wpf grid in grid selection change event am getting the selected row values. the problem is the values are as object. object myData = radGridView.SelectedItem; the object myData contains the row values. but i don know how to get values from the myData object

    Read the article

  • Asp.NET custom templated datalist throws argument out of range (index) on button press

    - by MrTortoise
    I have a class BaseTemplate public abstract class BaseTemplate : ITemplate This adds the controls, and provides abstract methods to implement in the inheriting class. The inheriting class then adds its html according to its data source and manages the data binding. This all works fine - I get the control appearing with properly parsed html. The problem is that the base class adds controls into the template that have their own CommandName arguments; the idea is that the class that implements the custom templated dataList will provide the logic of setting the Selected and Edit Indexes. This class also manages the data binding, etc. It sets all of the templates on the datalist in the Init method (which was another cause of this exception). The exception gets thrown when I hit one of these buttons - I have tried hooking up both their click and command events everywhere in case this was the problem. I have also ensured that their command names do not match any of the system ones. The stack trace does not include any references to my methods or objects which is why I am so stuck. It is the most unhelpful message I can imagine. The really frustrating thing is that I cannot get a breakpoint to fire - i.e. the problem is happening after I click the button, but before and of my code can execute. The last time this exception happened was when I had this code in a user control and was assigning the templates to the datalist in the PageLoad. I moved these into init to fix that problem; however, this is a problem that was there then and I have no idea what is causing it let alone how to solve it (and index out of range doesn't really help without knowing what index.) The Exception Details Exception Details: System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values. Parameter name: index The Stack Trace: [ArgumentOutOfRangeException: Specified argument was out of the range of valid values. Parameter name: index] System.Web.UI.ControlCollection.get_Item(Int32 index) +8665582 System.Web.UI.WebControls.DataList.GetItem(ListItemType itemType, Int32 repeatIndex) +8667655 System.Web.UI.WebControls.DataList.System.Web.UI.WebControls.IRepeatInfoUser.GetItemStyle(ListItemType itemType, Int32 repeatIndex) +11 System.Web.UI.WebControls.RepeatInfo.RenderVerticalRepeater(HtmlTextWriter writer, IRepeatInfoUser user, Style controlStyle, WebControl baseControl) +8640873 System.Web.UI.WebControls.RepeatInfo.RenderRepeater(HtmlTextWriter writer, IRepeatInfoUser user, Style controlStyle, WebControl baseControl) +27 System.Web.UI.WebControls.DataList.RenderContents(HtmlTextWriter writer) +208 System.Web.UI.WebControls.BaseDataList.Render(HtmlTextWriter writer) +30 System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27 System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +99 System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25 System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +134 System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +19 System.Web.UI.HtmlControls.HtmlForm.RenderChildren(HtmlTextWriter writer) +163 System.Web.UI.HtmlControls.HtmlContainerControl.Render(HtmlTextWriter writer) +32 System.Web.UI.HtmlControls.HtmlForm.Render(HtmlTextWriter output) +51 System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27 System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +99 System.Web.UI.HtmlControls.HtmlForm.RenderControl(HtmlTextWriter writer) +40 System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +134 System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +19 System.Web.UI.Page.Render(HtmlTextWriter writer) +29 System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27 System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +99 System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1266 The code Base class: public abstract class BaseTemplate : ITemplate { ListItemType _templateType; public BaseTemplate(ListItemType theTemplateType) { _templateType = theTemplateType; } public ListItemType ListItemType { get { return _templateType; } } #region ITemplate Members public void InstantiateIn(Control container) { PlaceHolder ph = new PlaceHolder(); container.Controls.Add(ph); Literal l = new Literal(); switch (_templateType) { case ListItemType.Header: { ph.Controls.Add(new LiteralControl(@"<table><tr>")); InstantiateInHeader(ph); ph.Controls.Add(new LiteralControl(@"</tr>")); break; } case ListItemType.Footer: { ph.Controls.Add(new LiteralControl(@"<tr>")); InstantiateInFooter(ph); ph.Controls.Add(new LiteralControl(@"</tr></table>")); break; } case ListItemType.Item: { ph.Controls.Add(new LiteralControl(@"<tr>")); InstantiateInItem(ph); ph.Controls.Add(new LiteralControl(@"<td>")); Button select = new Button(); select.ID = "btnSelect"; select.CommandName = "SelectRow"; select.Text = "Select"; ph.Controls.Add(select); ph.Controls.Add(new LiteralControl(@"</td>")); ph.Controls.Add(new LiteralControl(@"</tr>")); ph.DataBinding += new EventHandler(ph_DataBinding); break; } case ListItemType.AlternatingItem: { ph.Controls.Add(new LiteralControl(@"<tr>")); InstantiateInAlternatingItem(ph); ph.Controls.Add(new LiteralControl(@"<td>")); Button select = new Button(); select.ID = "btnSelect"; select.CommandName = "SelectRow"; select.Text = "Select"; ph.Controls.Add(select); ph.Controls.Add(new LiteralControl(@"</td>")); ph.Controls.Add(new LiteralControl(@"</tr>")); ph.DataBinding+=new EventHandler(ph_DataBinding); break; } case ListItemType.SelectedItem: { ph.Controls.Add(new LiteralControl(@"<tr>")); InstantiateInItem(ph); ph.Controls.Add(new LiteralControl(@"<td>")); Button edit = new Button(); edit.ID = "btnEdit"; edit.CommandName = "EditRow"; edit.Text = "Edit"; ph.Controls.Add(edit); Button delete = new Button(); delete.ID = "btnDelete"; delete.CommandName = "DeleteRow"; delete.Text = "Delete"; ph.Controls.Add(delete); ph.Controls.Add(new LiteralControl(@"</td>")); ph.Controls.Add(new LiteralControl(@"</tr>")); ph.DataBinding += new EventHandler(ph_DataBinding); break; } case ListItemType.EditItem: { ph.Controls.Add(new LiteralControl(@"<tr>")); InstantiateInEdit(ph); ph.Controls.Add(new LiteralControl(@"<td>")); Button save = new Button(); save.ID = "btnSave"; save.CommandName = "SaveRow"; save.Text = "Save"; ph.Controls.Add(save); Button cancel = new Button(); cancel.ID = "btnCancel"; cancel.CommandName = "CancelRow"; cancel.Text = "Cancel"; ph.Controls.Add(cancel); ph.Controls.Add(new LiteralControl(@"</td>")); ph.Controls.Add(new LiteralControl(@"</tr>")); ph.DataBinding += new EventHandler(ph_DataBinding); break; } case ListItemType.Separator: { InstantiateInSeperator(ph); break; } } } void ph_DataBinding(object sender, EventArgs e) { DataBindingOverride(sender, e); } /// <summary> /// the controls placed into the PlaceHolder will get wrapped in &lt;table&gt;&lt;tr&gt; &lt;/tr&gt;. I.e. you need to provide the column names wrapped in &lt;td&gt;&lt;/td&gt; tags. /// </summary> /// <param name="header"></param> public abstract void InstantiateInHeader(PlaceHolder ph); /// <summary> /// the controls will have a column added after them and so require each column to be properly wrapped in &lt;td&gt;&lt;/td&gt; tags. The &lt;tr&gt;&lt;/tr&gt; is handled in the base class. /// </summary> /// <param name="ph"></param> public abstract void InstantiateInItem(PlaceHolder ph); /// <summary> /// the controls will have a column added after them and so require each column to be properly wrapped in &lt;td&gt;&lt;/td&gt; tags. The &lt;tr&gt;&lt;/tr&gt; is handled in the base class. /// </summary> /// <param name="ph"></param> public abstract void InstantiateInAlternatingItem(PlaceHolder ph); /// <summary> /// the controls will have a column added after them and so require each column to be properly wrapped in &lt;td&gt;&lt;/td&gt; tags. The &lt;tr&gt;&lt;/tr&gt; is handled in the base class. /// </summary> /// <param name="ph"></param> public abstract void InstantiateInEdit(PlaceHolder ph); /// <summary> /// Any html used in the footer will have &lt;/tr&gt;&lt;table&gt; appended to the end. /// &lt;tr&gt; will be appended to the front. /// </summary> /// <param name="ph"></param> public abstract void InstantiateInFooter(PlaceHolder ph); /// <summary> /// the controls will have a column added after them and so require each column to be properly wrapped in &lt;td&gt;&lt;/td&gt; tags. The &lt;tr&gt;&lt;/tr&gt; is handled in the base class. /// Adds Delete and Edit Buttons after the table contents. /// </summary> /// <param name="ph"></param> public abstract void InstantiateInSelectedItem(PlaceHolder ph); /// <summary> /// The base class provides no &lt;tr&gt;&lt;/tr&gt; tags /// </summary> /// <param name="ph"></param> public abstract void InstantiateInSeperator(PlaceHolder ph); /// <summary> /// Use this method to bind the controls to their data. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public abstract void DataBindingOverride(object sender, EventArgs e); #endregion } Inheriting class: public class NominalGroupTemplate : BaseTemplate { public NominalGroupTemplate(ListItemType theListItemType) : base(theListItemType) { } public override void InstantiateInHeader(PlaceHolder ph) { ph.Controls.Add(new LiteralControl(@"<td>ID</td><td>Group</td><td>IsPositive</td>")); } public override void InstantiateInItem(PlaceHolder ph) { ph.Controls.Add(new LiteralControl(@"<td>")); Label lblID = new Label(); lblID.ID = "lblID"; ph.Controls.Add(lblID); ph.Controls.Add(new LiteralControl(@"</td><td>")); Label lblGroup = new Label(); lblGroup.ID = "lblGroup"; ph.Controls.Add(lblGroup); ph.Controls.Add(new LiteralControl(@"</td><td>")); CheckBox chkIsPositive = new CheckBox(); chkIsPositive.ID = "chkIsPositive"; chkIsPositive.Enabled = false; ph.Controls.Add(chkIsPositive); ph.Controls.Add(new LiteralControl(@"</td>")); } public override void InstantiateInAlternatingItem(PlaceHolder ph) { InstantiateInItem(ph); } public override void InstantiateInEdit(PlaceHolder ph) { ph.Controls.Add(new LiteralControl(@"<td>")); Label lblID = new Label(); lblID.ID = "lblID"; ph.Controls.Add(lblID); ph.Controls.Add(new LiteralControl(@"</td><td>")); TextBox txtGroup = new TextBox(); txtGroup.ID = "txtGroup"; txtGroup.Visible = true; txtGroup.Enabled = true ; ph.Controls.Add(txtGroup); ph.Controls.Add(new LiteralControl(@"</td><td>")); CheckBox chkIsPositive = new CheckBox(); chkIsPositive.ID = "chkIsPositive"; chkIsPositive.Visible = true; chkIsPositive.Enabled = true ; ph.Controls.Add(chkIsPositive); ph.Controls.Add(new LiteralControl(@"</td>")); } public override void InstantiateInFooter(PlaceHolder ph) { InstantiateInHeader(ph); } public override void InstantiateInSelectedItem(PlaceHolder ph) { ph.Controls.Add(new LiteralControl(@"<td>")); Label lblID = new Label(); lblID.ID = "lblID"; ph.Controls.Add(lblID); ph.Controls.Add(new LiteralControl(@"</td><td>")); TextBox txtGroup = new TextBox(); txtGroup.ID = "txtGroup"; txtGroup.Visible = true; txtGroup.Enabled = false; ph.Controls.Add(txtGroup); ph.Controls.Add(new LiteralControl(@"</td><td>")); CheckBox chkIsPositive = new CheckBox(); chkIsPositive.ID = "chkIsPositive"; chkIsPositive.Visible = true; chkIsPositive.Enabled = false; ph.Controls.Add(chkIsPositive); ph.Controls.Add(new LiteralControl(@"</td>")); } public override void InstantiateInSeperator(PlaceHolder ph) { } public override void DataBindingOverride(object sender, EventArgs e) { PlaceHolder ph = (PlaceHolder)sender; DataListItem li = (DataListItem)ph.NamingContainer; int id = Convert.ToInt32(DataBinder.Eval(li.DataItem, "ID")); string group = (string)DataBinder.Eval(li.DataItem, "Group"); bool isPositive = Convert.ToBoolean(DataBinder.Eval(li.DataItem, "IsPositive")); switch (this.ListItemType) { case ListItemType.Item: case ListItemType.AlternatingItem: { ((Label)ph.FindControl("lblID")).Text = id.ToString(); ((Label)ph.FindControl("lblGroup")).Text = group; ((CheckBox)ph.FindControl("chkIsPositive")).Text = isPositive.ToString(); break; } case ListItemType.EditItem: case ListItemType.SelectedItem: { ((TextBox)ph.FindControl("lblID")).Text = id.ToString(); ((TextBox)ph.FindControl("txtGroup")).Text = group; ((CheckBox)ph.FindControl("chkIsPositive")).Text = isPositive.ToString(); break; } } } } From here I added the control to a page the code behind public partial class NominalGroupbroke : System.Web.UI.UserControl { public void SetNominalGroupList(IList<BONominalGroup> theNominalGroups) { XElement data = Serialiser<BONominalGroup>.SerialiseObjectList(theNominalGroups); ViewState.Add("nominalGroups", data.ToString()); dlNominalGroup.DataSource = theNominalGroups; dlNominalGroup.DataBind(); } protected void Page_init() { dlNominalGroup.HeaderTemplate = new NominalGroupTemplate(ListItemType.Header); dlNominalGroup.ItemTemplate = new NominalGroupTemplate(ListItemType.Item); dlNominalGroup.AlternatingItemTemplate = new NominalGroupTemplate(ListItemType.AlternatingItem); dlNominalGroup.SeparatorTemplate = new NominalGroupTemplate(ListItemType.Separator); dlNominalGroup.SelectedItemTemplate = new NominalGroupTemplate(ListItemType.SelectedItem); dlNominalGroup.EditItemTemplate = new NominalGroupTemplate(ListItemType.EditItem); dlNominalGroup.FooterTemplate = new NominalGroupTemplate(ListItemType.Footer); } protected void Page_Load(object sender, EventArgs e) { dlNominalGroup.ItemCommand += new DataListCommandEventHandler(dlNominalGroup_ItemCommand); } void dlNominalGroup_Init(object sender, EventArgs e) { dlNominalGroup.HeaderTemplate = new NominalGroupTemplate(ListItemType.Header); dlNominalGroup.ItemTemplate = new NominalGroupTemplate(ListItemType.Item); dlNominalGroup.AlternatingItemTemplate = new NominalGroupTemplate(ListItemType.AlternatingItem); dlNominalGroup.SeparatorTemplate = new NominalGroupTemplate(ListItemType.Separator); dlNominalGroup.SelectedItemTemplate = new NominalGroupTemplate(ListItemType.SelectedItem); dlNominalGroup.EditItemTemplate = new NominalGroupTemplate(ListItemType.EditItem); dlNominalGroup.FooterTemplate = new NominalGroupTemplate(ListItemType.Footer); } void dlNominalGroup_DataBinding(object sender, EventArgs e) { } void deleteNominalGroup(int index) { XElement data = XElement.Parse(Convert.ToString( ViewState["nominalGroups"] )); IList<BONominalGroup> list = Serialiser<BONominalGroup>.DeserialiseObjectList(data); FENominalGroup.DeleteNominalGroup(list[index].ID); list.RemoveAt(index); data = Serialiser<BONominalGroup>.SerialiseObjectList(list); ViewState["nominalGroups"] = data.ToString(); dlNominalGroup.DataSource = list; dlNominalGroup.DataBind(); } void updateNominalGroup(DataListItem theItem) { XElement data = XElement.Parse(Convert.ToString( ViewState["nominalGroups"])); IList<BONominalGroup> list = Serialiser<BONominalGroup>.DeserialiseObjectList(data); BONominalGroup old = list[theItem.ItemIndex]; BONominalGroup n = new BONominalGroup(); byte id = Convert.ToByte(((TextBox)theItem.FindControl("lblID")).Text); string group = ((TextBox)theItem.FindControl("txtGroup")).Text; bool isPositive = Convert.ToBoolean(((CheckBox)theItem.FindControl("chkIsPositive")).Text); n.ID = id; n.Group = group; n.IsPositive = isPositive; FENominalGroup.UpdateNominalGroup(old, n); list[theItem.ItemIndex] = n; data = Serialiser<BONominalGroup>.SerialiseObjectList(list); ViewState["nominalGroups"] = data.ToString(); } void dlNominalGroup_ItemCommand(object source, DataListCommandEventArgs e) { DataList l = (DataList)source; switch (e.CommandName) { case "SelectRow": { if (l.EditItemIndex == -1) { l.SelectedIndex = e.Item.ItemIndex; l.EditItemIndex = -1; } break; } case "EditRow": { if (l.SelectedIndex == e.Item.ItemIndex) { l.EditItemIndex = e.Item.ItemIndex; } break; } case "DeleteRow": { deleteNominalGroup(e.Item.ItemIndex); l.EditItemIndex = -1; try { l.SelectedIndex = e.Item.ItemIndex; } catch { l.SelectedIndex = -1; } break; } case "CancelRow": { l.SelectedIndex = l.EditItemIndex; l.EditItemIndex = -1; break; } case "SaveRow": { updateNominalGroup(e.Item); try { l.SelectedIndex = e.Item.ItemIndex; } catch { l.SelectedIndex = -1; } l.EditItemIndex = -1; break; } } } Lots of code there, I'm afraid, but it should build. Thanks if anyone manages to spot my silliness. The BONominalGroup class (please ignore my crazy getHash override, I'm not proud of it). IAudit can just be an empty interface here and all will be fine. It used to inherit from another class, I have cleaned that out - so the serialization logic may be broken here. public class BONominalGroup { public BONominalGroup() #region Fields and properties private Int16 _ID; public Int16 ID { get { return _ID; } set { _ID = value; } } private string _group; public string Group { get { return _group; } set { _group = value; } } private bool _isPositve; public bool IsPositive { get { return _isPositve; } set { _isPositve = value; } } #endregion public override bool Equals(object obj) { bool retVal = false; BONominalGroup ng = obj as BONominalGroup; if (ng!=null) if (ng._group == this._group && ng._ID == this.ID && ng.IsPositive == this.IsPositive) { retVal = true; } return retVal; } public override int GetHashCode() { return ToString().GetHashCode(); } public override string ToString() { return "BONominalGroup{ID:" + this.ID.ToString() + ",Group:" + this.Group.ToString() + ",IsPositive:" + this.IsPositive.ToString() + "," + "}"; } #region IXmlSerializable Members public override void ReadXml(XmlReader reader) { reader.ReadStartElement("BONominalGroup"); this.ID = Convert.ToByte(reader.ReadElementString("id")); this.Group = reader.ReadElementString("group"); this.IsPositive = Convert.ToBoolean(reader.ReadElementString("isPositive")); base.ReadXml(reader); reader.ReadEndElement(); } public override void WriteXml(XmlWriter writer) { writer.WriteElementString("id", this.ID.ToString()); writer.WriteElementString("group", this.Group); writer.WriteElementString("isPositive", this.IsPositive.ToString()); // writer.WriteStartElement("BOBase"); // base.WriteXml(writer); writer.WriteEndElement(); } #endregion }

    Read the article

< Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >