Search Results

Search found 91 results on 4 pages for 'datagridtextcolumn'.

Page 4/4 | < Previous Page | 1 2 3 4 

  • WPF - How to bind a DataGridTemplateColumn

    - by Andy T
    Hi, I am trying to get the name of the property associated with a particular DataGridColumn, so that I can then do some stuff based on that. This function is called when the user clicks context menu item on the column's header... This is fine for the out-of-the-box ready-rolled column types like DataGridTextColumn, since they are bound, but the problem is that some of my columns are DataGridTemplateColumns, which are not bound. private void GroupByField_Click (object sender, RoutedEventArgs e){ MenuItem mi = (MenuItem)sender; ContextMenu cm = (ContextMenu) mi.Parent; DataGridColumnHeader dgch = (DataGridColumnHeader) cm.PlacementTarget; DataGridBoundColumn dgbc = (DataGridBoundColumn) dgch.Column; Binding binding = (Binding) dgbc.Binding; string BoundPropName = binding.Path.Path; //Do stuff based on bound property name here... } So, take for example my 'Name' column... it's a DataGridTemplateColumn (since it has an image and some other stuff in there). Therefore, it is not actually bound to the 'Name' property... but I would like to be, so that the above code will work. My question is two-part, really: 1) Is it possible to make a DataGridTemplateColumn be BOUND, so that the above code would work? Can I bind it somehow to a property? 2) Or do I need to something entirely different, and change the code above? Thanks in advance! AT

    Read the article

  • Styling columns based on DataGridTemplateColumn in a WPF DataGrid

    - by nareshbhatia
    I am using a WPF DataGrid where one of the columns has a requirement to show an "Edit" hyperlink if the row is editable - this is indicated by a boolean flag in the backing model for the row. I was able to achieve this using a DataGridTemplateColumn - no problems. However an additional requirement on the entire row is not to show any highlights when the row is selected (this is a blue background by default). I have been able to achieve this on other columns by defining the DataGridCell style with a transparent background, e.g. <DataGridTextColumn Header="Id" Binding="{Binding Path=Id}" HeaderStyle="{StaticResource DataGridColumnHeaderStyle}" CellStyle="{StaticResource DataGridCellStyle}" /> where DataGridCellStyle is defined as follows: <Style x:Key="DataGridCellStyle" TargetType="{x:Type DataGridCell}"> <Setter Property="Background" Value="Transparent" /> ... </Style> However the column in question, a DataGridTemplateColumn, does not offer a "CellStyle" attribute which I can use for turning off selection highlights. So my question is how to set the cell style when using a DataGridTemplateColumn? Here's my implementation of the column which satisfies the first requirement (i.e. showing an "Edit" hyperlink if the row is editable): <DataGridTemplateColumn Header="Actions" HeaderStyle="{StaticResource CenterAlignedColumnHeaderStyle}"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <TextBlock Visibility="{Binding Path=Editable, Converter={StaticResource convVisibility}}" Style="{StaticResource CenterAlignedElementStyle}"> <Hyperlink Command="..." CommandParameter="{Binding}"> <TextBlock Text="Edit" /> </Hyperlink> </TextBlock> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> Thanks.

    Read the article

  • Binding DataGridComboBoxColumn to a one to many entity framework relation

    - by Cristian
    I have two tables in the model, one table contains entries related to the other table in a one to many relations, for example: Table User ID Name Table Comments ID UserID Title Text I want to show a datagrid in a WPF window with two columns, one text column with the User name and another column with a combobox showing all the comments made by the user. The datagrid definition is like this: <DataGrid AutoGenerateColumns="False" [layout options...] Name="dataGrid1" ItemsSource="{Binding}"> <DataGrid.Columns> <DataGridTextColumn Header="Name" Binding="{Binding Path=Name}"/> <DataGridComboBoxColumn Header="Comments" SelectedValueBinding="{Binding Path=UserID}" SelectedValuePath="ID" DisplayMemberPath="Title" ItemsSource="{Binding Path=Comments}" /> </DataGrid.Columns> </DataGrid> in the code I assign the DataContext like this: dataGrid1.DataContext = entities.Users; The entity User has a property named Comments that leads to all the comments made by the user. The queries are returning data and the user names are shown but the combobox is not being filled. May be the approach is totally wrong or I'm just missing a very simple point here, I'm opened to learn better methods to do this. Thanks

    Read the article

  • DataGridComboBoxColumn was not found

    - by Budda
    The System.Windows.Controls.Data.DataGrid is used in my Silverlight application, but on attempt to add 'DataGridComboBoxColumn' column to the grid the following error messages are obtained: Error 1 The tag 'DataGridComboBoxColumn' does not exist in XML namespace 'clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data'. C:\Project\Budda\VFMElita\VfmElitaView\Pages\SquadView.xaml 140 22 VfmElitaView Error 2 The type 'data:DataGridComboBoxColumn' was not found. Verify that you are not missing an assembly reference and that all referenced assemblies have been built. C:\Project\Budda\VFMElita\VfmElitaView\Pages\SquadView.xaml 142 22 VfmElitaView Here is my "header" of the xaml-file: Here is grid: <StackPanel Grid.Row="1" Grid.Column="0" Grid.RowSpan="2"> <TextBlock Text="????"/> <data:DataGrid AutoGenerateColumns="False" ItemsSource="{Binding FieldPlayers}"> <data:DataGrid.Columns> <!--<data:DataGridTemplateColumn Header="#"> <data:DataGridTemplateColumn.CellTemplate> <DataTemplate> <TextBlock Margin="4" Loaded="TextBlock_Loaded"/> </DataTemplate> </data:DataGridTemplateColumn.CellTemplate> </data:DataGridTemplateColumn>--> <data:DataGridTextColumn Header="?" Binding="{Binding Number}"/> <data:DataGridComboBoxColumn> - that doesn't work </data:DataGridComboBoxColumn> </data:DataGrid.Columns> </data:DataGrid> </StackPanel> What is required to get 'DataGridComboBoxColumn' workable? Any help is welcome. Thanks.

    Read the article

  • Changing label content programmatically from within a DataTemplate used in a DataGrid column header

    - by iimpact
    I'm dynamically creating DataGrid columns (based on an event from my ViewModel) and programmatically adding them to an existing DataGrid. Each column uses a generic HeaderTemplate by setting it to a DataTemplate that has been identified in the xaml. The DataTemplate contains two labels in which needs their content needs to be changed upon creation of the DataGrid column. How would this be done? I understand that the DataTemplate uses the ContentPresenter but I am having trouble accessing it within a dynamically created DataGrid column. Code is as follows: xaml: (template used to format the DataGrid column header): <DataTemplate x:Key="columnTemplate"> <StackPanel> <Label Padding="0" Name="labelA"/> <Separator HorizontalAlignment="Stretch"/> <Label Padding="0" Name="labelB"/> </StackPanel> </DataTemplate> c#: (used to dynamically create a DataGrid column and add it to an existing DataGrid) var dataTemplate = FindResource("columnTemplate") as DataTemplate; var column = new DataGridTextColumn(); column.HeaderTemplate = dataTemplate; DataGrid1.Columns.Add(column); I would like to then access both labelA and labelB and change the content.

    Read the article

  • WPF DataGrid binding difficulties

    - by Jasmin Pvvlovic
    This is the class: public class TrainingData { public string Training { get; set; } } And this is the rest of the code in MainWindow: Excel.Workbook xlWorkbook = xlApp.Workbooks.Open("D:/excel.xlsx"); Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1]; Excel.Range xlRange = xlWorksheet.UsedRange; List <TrainingData> tData= new List <TrainingData>(); int rowCount = xlRange.Rows.Count; int colCount = xlRange.Columns.Count; //int k = 0; for (int i = 1; i <= rowCount; i++) { tData.Add(new TrainingData() { Training = xlRange.Cells[i, 1].Value2.ToString() }); //MessageBox.Show(tData[k].Training); //k++; } Prikaz.ItemsSource = tData; DataGrid: <DataGrid AutoGenerateColumns="False" Height="120" HorizontalAlignment="Left" Margin="12,12,0,0" Name="Prikaz" VerticalAlignment="Top" Width="105" ItemsSource="{Binding}"> <DataGrid.Columns> <DataGridTextColumn Header="Header" /> </DataGrid.Columns> </DataGrid>` So, Prikaz is my DataGrid. tData is List of TrainingData objects. If I uncomment these three lines I can test if I have imported information from excel file correctly, and yes, that works just fine. So why am I getting empty DataGrid? It has right number of rows and only one column, that's ok, but there are no data in it. I used this line: Prikaz.ItemsSource = tData; to bind my objects list and DataGrid. Training is declared public so it should be present in DataGrid. What could be causing the problem?

    Read the article

  • Calling a datatrigger for a radio button inside a datagrid

    - by Farax
    I have a datagrid with one column having a radio button. I want to set the GroupName when a certain condition is reached. Below is the code <Custom:DataGrid.Columns> <!-- ONLY ENABLED WHEN THE ITEM TYPE IS SINGLESELECT OR SINGLESELECT WITH ADDIOTIONAL DATA--> <Custom:DataGridTemplateColumn CanUserResize="False" MinWidth="20" > <Custom:DataGridTemplateColumn.CellTemplate> <DataTemplate> <RadioButton IsChecked="{Binding IsChecked}" d:DesignWidth="16" d:DesignHeight="16" GroupName="SingleChoiceSelection" Template="{DynamicResource RadioButtonTemplate}" Background="{DynamicResource BackgroundNew}" BorderBrush="#FF7A7171" Foreground="#FF6C6C6C" Margin="0" /> </DataTemplate> </Custom:DataGridTemplateColumn.CellTemplate> </Custom:DataGridTemplateColumn> <Custom:DataGridTextColumn Header="Choices" Binding="{Binding ChoiceText}" CellStyle="{DynamicResource DataGridCellStyle2}" MinWidth="150" /> </Custom:DataGrid.Columns> </Custom:DataGrid> The ItemSource contains a property called isChecked and I want to change the foreground color when isChecked is changed to true. How do i do this with a datatrigger?

    Read the article

  • How do I bind arrays to columns in a WPF datagrid

    - by user1432917
    I have a Log object that contains a list of Curve objects. Each curve has a Name property and an array of doubles. I want the Name to be in the column header and the data below it. I have a user control with a datagid. Here is the XAML; <UserControl x:Class="WellLab.UI.LogViewer" 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="500" d:DesignWidth="500"> <Grid> <StackPanel Height="Auto" HorizontalAlignment="Stretch" Margin="0" Name="stackPanel1" VerticalAlignment="Stretch" Width="Auto"> <ToolBarTray Height="26" Name="toolBarTray1" Width="Auto" /> <ScrollViewer Height="Auto" Name="scrollViewer1" Width="Auto" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Visible" CanContentScroll="True" Background="#E6ABA4A4"> <DataGrid AutoGenerateColumns="True" Height="Auto" Name="logDataGrid" Width="Auto" ItemsSource="{Binding}" HorizontalAlignment="Left"> </DataGrid> </ScrollViewer> </StackPanel> </Grid> In the code behind I have figured out how to create columns and name them, but I have not figured out how to bind the data. public partial class LogViewer { public LogViewer(Log log) { InitializeComponent(); foreach (var curve in log.Curves) { var data = curve.GetData(); var col = new DataGridTextColumn { Header = curve.Name }; logDataGrid.Columns.Add(col); } } } I wont even show the code I tried to use to bind the array "data", since nothing even came close. I am sure I am missing something simple, but after hours of searching the web, I have to come begging for an answer.

    Read the article

  • WPF Binding Path=/ not working?

    - by Mark
    I've set up my DataContext like this: <Window.DataContext> <c:DownloadManager /> </Window.DataContext> Where DownloadManager is Enumerable<DownloadItem>. Then I set my DataGrid like this: <DataGrid Name="dataGrid1" ItemsSource="{Binding Path=/}" ... So that it should list all the DownloadItems, right? So I should be able to set my columns like: <DataGridTextColumn Binding="{Binding Path=Uri, Mode=OneWay}" Where Uri is a property of the DownloadItem. But it doesn't seem to like this. In the visual property editor, it doesn't recognize Uri is a valid property, so I'm guessing I'm doing something wrong. It was working before, when I had the data grid binding to Values, but then I took that enumerable out of the DownloadManager and made itself enumerable. How do I fix this? PS: By "doesn't work" I mean it doesn't list any items. I've added some to the constructor of the DM, so it shouldn't be empty.

    Read the article

  • WPF RowDetailsTemplate width issue

    - by Ed Courtenay
    Apologies if this is a dupe, but I can't seem to find a rational solution for what must be a fairly simple issue. <Window x:Class="FeedTest.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"> <Window.Resources> <XmlNamespaceMappingCollection x:Key="map"> <XmlNamespaceMapping Prefix="media" Uri="http://search.yahoo.com/mrss/" /> </XmlNamespaceMappingCollection> <XmlDataProvider x:Key="newsFeed" XPath="//item[string-length(title)>0]" Source="http://newsrss.bbc.co.uk/rss/newsonline_uk_edition/uk/rss.xml" /> <DataTemplate x:Key="rowDetailTemplate"> <Border BorderThickness="2"> <StackPanel Orientation="Horizontal"> <Image Source="{Binding XPath=media:thumbnail/@url}" Width="66" Height="49" /> <StackPanel Orientation="Vertical" Margin="5"> <TextBlock Text="{Binding XPath=description}" TextWrapping="Wrap" /> </StackPanel> </StackPanel> </Border> </DataTemplate> <Style TargetType="{x:Type DataGrid}"> <Setter Property="GridLinesVisibility" Value="None" /> </Style> </Window.Resources> <Grid Binding.XmlNamespaceManager="{StaticResource map}"> <DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Source={StaticResource newsFeed}}" RowDetailsVisibilityMode="VisibleWhenSelected" RowDetailsTemplate="{StaticResource rowDetailTemplate}"> <DataGrid.Columns> <DataGridTextColumn Header="Title" Binding="{Binding XPath=title}" MinWidth="150" Width="*" /> </DataGrid.Columns> </DataGrid> </Grid> The attached XAML gets a news feed, and displays the title of each item in a DataGrid. Selecting an item shows the RowDetailsTemplate which is where my problem lies - why does the RowDetailsTemplate expand beyond the width of the containing DataGrid (thus forcing a horizontal scrollbar), and more importantly, how do I stop it doing this? Many thanks.

    Read the article

  • Silverlight DataGrid's sort by column doesn't update programmatically changed cells

    - by David Seiler
    For my first Silverlight app, I've written a program that sends user-supplied search strings to the Flickr REST API and displays the results in a DataGrid. Said grid is defined like so: <data:DataGrid x:Name="PhotoGrid" AutoGenerateColumns="False"> <data:DataGrid.Columns> <data:DataGridTextColumn Header="Photo Title" Binding="{Binding Title}" CanUserSort="True" CanUserReorder="True" CanUserResize="True" IsReadOnly="True" /> <data:DataGridTemplateColumn Header="Photo" SortMemberPath="ImageUrl"> <data:DataGridTemplateColumn.CellTemplate> <DataTemplate> <StackPanel Orientation="Horizontal" VerticalAlignment="Center"> <TextBlock Text="Click here to show image" MouseLeftButtonUp="ShowPhoto"/> <Image Visibility="Collapsed" MouseLeftButtonUp="HidePhoto"/> </StackPanel> </DataTemplate> </data:DataGridTemplateColumn.CellTemplate> </data:DataGridTemplateColumn> </data:DataGrid.Columns> </data:DataGrid> It's a simple two-column table. The first column contains the title of the photo, while the second contains the text 'Click here to show image'. Clicks there call ShowPhoto(), which updates the Image element's Source property with a BitmapImage derived from the URI of the Flickr photo, and sets the image's visibility to Visible. Clicking on the image thus revealed hides it again. All of this was easy to implement and works perfectly. But whenever I click on one of the column headers to sort by that column, the cells that I've updated in this way do not change. The rest of the DataGrid is resorted and updated appropriately, but those cells remain behind, detached from the rest of their row. This is very strange, and not at all what I want. What am I doing wrong? Should I be freshening the DataGrid somehow in response to the sort event, and if so how? Or if I'm not supposed to be messing with the contents of the grid directly, what's the right way to get the behavior I want?

    Read the article

  • WPF 4 Datagrid with ComboBox

    - by Doug
    I have a WPF 4 app with a ComboBox embedded in a DataGrid. The ComboBox is in a template column that displays the combobox when in edit mode but just a TextBlock otherwise. If I edit the cell and pick a new value from the combobox, when leaving the cell, the TextBlock in view mode does not reflect the new value. Ultimately, the new value gets saved and is displayed when the window is refreshed but it does not happen while still editing in the grid. Here are the parts that are making this more complicated. The grid and the combobox are bound to different ItemsSource from the EnityFramework which is tied to my database. For this problem, the grid is displaying project members. The project member name can be picked from the combobox which gives a list of all company employees. Any ideas on how to tie the view mode of the DataGridColumnTemplate to the edit value when they are pointing to different DataSources? Relevant XAML <Window.Resources> <ObjectDataProvider x:Key="EmployeeODP" /> </Window.Resources> <StackPanel> <DataGrid Name="teamProjectGrid" AutoGenerateColumns="false" ItemsSource="{Binding Path=ProjectMembers}" <DataGrid.Columns> <DataGridTemplateColumn Header="Name" x:Name="colProjectMember"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <TextBlock Text="{Binding Path=ProjectMemberFullName}" /> </DataTemplate> </DataGridTemplateColumn.CellTemplate> <DataGridTemplateColumn.CellEditingTemplate> <DataTemplate> <ComboBox x:Name="ProjectMemberCombo" IsReadOnly="True" DisplayMemberPath="FullName" SelectedValue="{Binding Path=Employee}" ItemsSource="{Binding Source={StaticResource EmployeeODP}}" /> </DataTemplate> </DataGridTemplateColumn.CellEditingTemplate> </DataGridTemplateColumn> <DataGridTextColumn x:Name="colProjectRole" Binding="{Binding Path=ProjectRole}" Header="Role" /> </DataGrid.Columns> </DataGrid> </StackPanel> Relevant Code Behind this.DataContext = new MyEntityLibrary.MyProjectEntities(); ObjectDataProvider EmployeeODP= (ObjectDataProvider)FindResource("EmployeeODP"); if (EmployeeODP != null) { EmployeeODP.ObjectInstance = this.DataContext.Employees; }

    Read the article

  • wpftoolkit DataGridTemplateColumn Template binding

    - by Guillaume
    I want my datagrid columns to share a cell/celledit template. I have the solution do that (thanks to WPF DataGridTemplateColumn shared template?). Now what I would love to is improving the readability by avoiding all the node nesting. My current view looks like that: <wpftk:DataGrid ItemsSource="{Binding Tests}" AutoGenerateColumns="False"> <wpftk:DataGrid.Resources> <DataTemplate x:Key="CustomCellTemplate"> <TextBlock Text="{TemplateBinding Content}"/> </DataTemplate> <DataTemplate x:Key="CustomCellEditingTemplate"> <TextBox Text="{TemplateBinding Content}"></TextBox> </DataTemplate> </wpftk:DataGrid.Resources> <wpftk:DataGrid.Columns> <wpftk:DataGridTemplateColumn Header="Start Date"> <wpftk:DataGridTemplateColumn.CellTemplate> <DataTemplate> <ContentPresenter ContentTemplate="{StaticResource CustomCellTemplate}" Content="{Binding StartDate}"/> </DataTemplate> </wpftk:DataGridTemplateColumn.CellTemplate> <wpftk:DataGridTemplateColumn.CellEditingTemplate> <DataTemplate> <ContentPresenter ContentTemplate="{StaticResource CustomCellEditingTemplate}" Content="{Binding StartDate}"/> </DataTemplate> </wpftk:DataGridTemplateColumn.CellEditingTemplate> </wpftk:DataGridTemplateColumn> <!--and again the whole block above for each columns...--> </wpftk:DataGrid.Columns> </wpftk:DataGrid> What I would like to achieve is to bind the value at the DataGridTemplateColumn level and propagate it to the template level. Anyone know how to do that? What I tried to do is something like that: <wpftk:DataGrid ItemsSource="{Binding Tests}" AutoGenerateColumns="False"> <wpftk:DataGrid.Resources> <DataTemplate x:Key="CustomCellTemplate"> <TextBlock Text="{Binding}"/> </DataTemplate> <DataTemplate x:Key="CustomCellEditingTemplate"> <TextBox Text="{Binding}"></TextBox> </DataTemplate> </wpftk:DataGrid.Resources> <wpftk:DataGrid.Columns> <wpftk:DataGridTemplateColumn Header="Start Date" Binding="{Binding StartDate}" CellTemplate="{StaticResource CustomCellTemplate}" CellEditingTemplate="{StaticResource CustomCellEditingTemplate}"/> <wpftk:DataGridTemplateColumn Header="End Date" Binding="{Binding EndDate}" CellTemplate="{StaticResource CustomCellTemplate}" CellEditingTemplate="{StaticResource CustomCellEditingTemplate}"/> </wpftk:DataGrid.Columns> </wpftk:DataGrid> Obviously the binding porperty is not a valid property of the DataGridTemplateColumn but maybe by playing with the datacontext and some relative source could do the trick but frankly I can't find a way to implement that. Not sure if what I want is possible and i'm willing to accept a "no way you can do that" as an answer NOTE: The TextBlock/TextBox in the template is just for test (the real template is much more complex) DataGridTextColumn will not do the trick Thanks in advance

    Read the article

  • Silverlight 4 Twitter Client &ndash; Part 6

    - by Max
    In this post, we are going to look into implementing lists into our twitter application and also about enhancing the data grid to display the status messages in a pleasing way with the profile images. Twitter lists are really cool feature that they recently added, I love them and I’ve quite a few lists setup one for DOTNET gurus, SQL Server gurus and one for a few celebrities. You can follow them here. Now let us move onto our tutorial. 1) Lists can be subscribed to in two ways, one can be user’s own lists, which he has created and another one is the lists that the user is following. Like for example, I’ve created 3 lists myself and I am following 1 other lists created by another user. Both of them cannot be fetched in the same api call, its a two step process. 2) In the TwitterCredentialsSubmit method we’ve in Home.xaml.cs, let us do the first api call to get the lists that the user has created. For this the call has to be made to https://twitter.com/<TwitterUsername>/lists.xml. The API reference is available here. myService1.AllowReadStreamBuffering = true; myService1.UseDefaultCredentials = false; myService1.Credentials = new NetworkCredential(GlobalVariable.getUserName(), GlobalVariable.getPassword()); myService1.DownloadStringCompleted += new DownloadStringCompletedEventHandler(ListsRequestCompleted); myService1.DownloadStringAsync(new Uri("https://twitter.com/" + GlobalVariable.getUserName() + "/lists.xml")); 3) Now let us look at implementing the event handler – ListRequestCompleted for this. public void ListsRequestCompleted(object sender, System.Net.DownloadStringCompletedEventArgs e) { if (e.Error != null) { StatusMessage.Text = "This application must be installed first."; parseXML(""); } else { //MessageBox.Show(e.Result.ToString()); parseXMLLists(e.Result.ToString()); } } 4) Now let us look at the parseXMLLists in detail xdoc = XDocument.Parse(text); var answer = (from status in xdoc.Descendants("list") select status.Element("name").Value); foreach (var p in answer) { Border bord = new Border(); bord.CornerRadius = new CornerRadius(10, 10, 10, 10); Button b = new Button(); b.MinWidth = 70; b.Background = new SolidColorBrush(Colors.Black); b.Foreground = new SolidColorBrush(Colors.Black); //b.Width = 70; b.Height = 25; b.Click += new RoutedEventHandler(b_Click); b.Content = p.ToString(); bord.Child = b; TwitterListStack.Children.Add(bord); } So here what am I doing, I am just dynamically creating a button for each of the lists and put them within a StackPanel and for each of these buttons, I am creating a event handler b_Click which will be fired on button click. We will look into this method in detail soon. For now let us get the buttons displayed. 5) Now the user might have some lists to which he has subscribed to. We need to create a button for these as well. In the end of TwitterCredentialsSubmit method, we need to make a call to http://api.twitter.com/1/<TwitterUsername>/lists/subscriptions.xml. Reference is available here. The code will look like this below. myService2.AllowReadStreamBuffering = true; myService2.UseDefaultCredentials = false; myService2.Credentials = new NetworkCredential(GlobalVariable.getUserName(), GlobalVariable.getPassword()); myService2.DownloadStringCompleted += new DownloadStringCompletedEventHandler(ListsSubsRequestCompleted); myService2.DownloadStringAsync(new Uri("http://api.twitter.com/1/" + GlobalVariable.getUserName() + "/lists/subscriptions.xml")); 6) In the event handler – ListsSubsRequestCompleted, we need to parse through the xml string and create a button for each of the lists subscribed, let us see how. I’ve taken only the “full_name”, you can choose what you want, refer the documentation here. Note the point that the full_name will have @<UserName>/<ListName> format – this will be useful very soon. xdoc = XDocument.Parse(text); var answer = (from status in xdoc.Descendants("list") select status.Element("full_name").Value); foreach (var p in answer) { Border bord = new Border(); bord.CornerRadius = new CornerRadius(10, 10, 10, 10); Button b = new Button(); b.Background = new SolidColorBrush(Colors.Black); b.Foreground = new SolidColorBrush(Colors.Black); //b.Width = 70; b.MinWidth = 70; b.Height = 25; b.Click += new RoutedEventHandler(b_Click); b.Content = p.ToString(); bord.Child = b; TwitterListStack.Children.Add(bord); } Please note, I am setting the button width to be auto based on the content and also giving it a midwidth value. I wanted to create a rounded corner buttons, but for some reason its not working. Also add this StackPanel – TwitterListStack of the Home.xaml <StackPanel HorizontalAlignment="Center" Orientation="Horizontal" Name="TwitterListStack"></StackPanel> After doing this, you would get a series of buttons in the top of the home page. 7) Now the button click event handler – b_Click, in this method, once the button is clicked, I call another method with the content string of the button which is clicked as the parameter. Button b = (Button)e.OriginalSource; getListStatuses(b.Content.ToString()); 8) Now the getListsStatuses method: toggleProgressBar(true); WebRequest.RegisterPrefix("http://", System.Net.Browser.WebRequestCreator.ClientHttp); WebClient myService = new WebClient(); myService.AllowReadStreamBuffering = true; myService.UseDefaultCredentials = false; myService.DownloadStringCompleted += new DownloadStringCompletedEventHandler(TimelineRequestCompleted); if (listName.IndexOf("@") > -1 && listName.IndexOf("/") > -1) { string[] arrays = null; arrays = listName.Split('/'); arrays[0] = arrays[0].Replace("@", " ").Trim(); //MessageBox.Show(arrays[0]); //MessageBox.Show(arrays[1]); string url = "http://api.twitter.com/1/" + arrays[0] + "/lists/" + arrays[1] + "/statuses.xml"; //MessageBox.Show(url); myService.DownloadStringAsync(new Uri(url)); } else myService.DownloadStringAsync(new Uri("http://api.twitter.com/1/" + GlobalVariable.getUserName() + "/lists/" + listName + "/statuses.xml")); Please note that the url to look at will be different based on the list clicked – if its user created, the url format will be http://api.twitter.com/1/<CurentUser>/lists/<ListName>/statuses.xml But if it is some lists subscribed, it will be http://api.twitter.com/1/<ListOwnerUserName>/lists/<ListName>/statuses.xml The first one is pretty straight forward to implement, but if its a list subscribed, we need to split the listName string to get the list owner and list name and user them to form the string. So that is what I’ve done in this method, if the listName has got “@” and “/” I build the url differently. 9) Until now, we’ve been using only a few nodes of the status message xml string, now we will look to fetch a new field - “profile_image_url”. Images in datagrid – COOL. So for that, we need to modify our Status.cs file to include two more fields one string another BitmapImage with get and set. public string profile_image_url { get; set; } public BitmapImage profileImage { get; set; } 10) Now let us change the generic parseXML method which is used for binding to the datagrid. public void parseXML(string text) { XDocument xdoc; xdoc = XDocument.Parse(text); statusList = new List<Status>(); statusList = (from status in xdoc.Descendants("status") select new Status { ID = status.Element("id").Value, Text = status.Element("text").Value, Source = status.Element("source").Value, UserID = status.Element("user").Element("id").Value, UserName = status.Element("user").Element("screen_name").Value, profile_image_url = status.Element("user").Element("profile_image_url").Value, profileImage = new BitmapImage(new Uri(status.Element("user").Element("profile_image_url").Value)) }).ToList(); DataGridStatus.ItemsSource = statusList; StatusMessage.Text = "Datagrid refreshed."; toggleProgressBar(false); } We are here creating a new bitmap image from the image url and creating a new Status object for every status and binding them to the data grid. Refer to the Twitter API documentation here. You can choose any column you want. 11) Until now, we’ve been using the auto generate columns for the data grid, but if you want it to be really cool, you need to define the columns with templates, etc… <data:DataGrid AutoGenerateColumns="False" Name="DataGridStatus" Height="Auto" MinWidth="400"> <data:DataGrid.Columns> <data:DataGridTemplateColumn Width="50" Header=""> <data:DataGridTemplateColumn.CellTemplate> <DataTemplate> <Image Source="{Binding profileImage}" Width="50" Height="50" Margin="1"/> </DataTemplate> </data:DataGridTemplateColumn.CellTemplate> </data:DataGridTemplateColumn> <data:DataGridTextColumn Width="Auto" Header="User Name" Binding="{Binding UserName}" /> <data:DataGridTemplateColumn MinWidth="300" Width="Auto" Header="Status"> <data:DataGridTemplateColumn.CellTemplate> <DataTemplate> <TextBlock TextWrapping="Wrap" Text="{Binding Text}"/> </DataTemplate> </data:DataGridTemplateColumn.CellTemplate> </data:DataGridTemplateColumn> </data:DataGrid.Columns> </data:DataGrid> I’ve used only three columns – Profile image, Username, Status text. Now our Datagrid will look super cool like this. Coincidentally,  Tim Heuer is on the screenshot , who is a Silverlight Guru and works on SL team in Microsoft. His blog is really super. Here is the zipped file for all the xaml, xaml.cs & class files pages. Ok let us stop here for now, will look into implementing few more features in the next few posts and then I am going to look into developing a ASP.NET MVC 2 application. Hope you all liked this post. If you have any queries / suggestions feel free to comment below or contact me. Cheers! Technorati Tags: Silverlight,LINQ,Twitter API,Twitter,Silverlight 4

    Read the article

  • Databind a datagrid header combobox from ViewModel

    - by Mike
    I've got a Datagrid with a column defined as this: <Custom:DataGridTextColumn HeaderStyle="{StaticResource ComboBoxHeader}" Width="Auto" Header="Type" Binding="{Binding Path=Type}" IsReadOnly="True" /> The ComboBoxHeader style is defined in a resource dictionary as this: <Style x:Key="ComboBoxHeader" TargetType="{x:Type my:DataGridColumnHeader}"> <Setter Property="VerticalContentAlignment" Value="Center"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type my:DataGridColumnHeader}"> <ControlTemplate.Resources> <Storyboard x:Key="ShowFilterControl"> <ObjectAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="filterComboBox" Storyboard.TargetProperty="(UIElement.Visibility)"> <DiscreteObjectKeyFrame KeyTime="00:00:00" Value="{x:Static Visibility.Visible}"/> <DiscreteObjectKeyFrame KeyTime="00:00:00.5000000" Value="{x:Static Visibility.Visible}"/> </ObjectAnimationUsingKeyFrames> <ColorAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="filterComboBox" Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)"> <SplineColorKeyFrame KeyTime="00:00:00" Value="Transparent"/> <SplineColorKeyFrame KeyTime="00:00:00.5000000" Value="White"/> </ColorAnimationUsingKeyFrames> </Storyboard> <Storyboard x:Key="HideFilterControl"> <ObjectAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="filterComboBox" Storyboard.TargetProperty="(UIElement.Visibility)"> <DiscreteObjectKeyFrame KeyTime="00:00:00.4000000" Value="{x:Static Visibility.Collapsed}"/> </ObjectAnimationUsingKeyFrames> <ColorAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="filterComboBox" Storyboard.TargetProperty="(UIElement.OpacityMask).(SolidColorBrush.Color)"> <SplineColorKeyFrame KeyTime="00:00:00" Value="Black"/> <SplineColorKeyFrame KeyTime="00:00:00.4000000" Value="#00000000"/> </ColorAnimationUsingKeyFrames> </Storyboard> </ControlTemplate.Resources> <my:DataGridHeaderBorder x:Name="dataGridHeaderBorder" Margin="0" VerticalAlignment="Top" Height="31" IsClickable="{TemplateBinding CanUserSort}" IsHovered="{TemplateBinding IsMouseOver}" IsPressed="{TemplateBinding IsPressed}" SeparatorBrush="{TemplateBinding SeparatorBrush}" SeparatorVisibility="{TemplateBinding SeparatorVisibility}" SortDirection="{TemplateBinding SortDirection}" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Padding="{TemplateBinding Padding}" Grid.ColumnSpan="1"> <Grid x:Name="grid" Width="Auto" Height="Auto" RenderTransformOrigin="0.5,0.5"> <Grid.RenderTransform> <TransformGroup> <ScaleTransform/> <SkewTransform/> <RotateTransform/> <TranslateTransform/> </TransformGroup> </Grid.RenderTransform> <Grid.ColumnDefinitions> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <ContentPresenter x:Name="contentPresenter" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" ContentStringFormat="{TemplateBinding ContentStringFormat}" ContentTemplate="{TemplateBinding ContentTemplate}"> <ContentPresenter.Content> <MultiBinding Converter="{StaticResource headerConverter}"> <MultiBinding.Bindings> <Binding ElementName="filterComboBox" Path="Text" /> <Binding RelativeSource="{RelativeSource TemplatedParent}" Path="Content" /> </MultiBinding.Bindings> </MultiBinding> </ContentPresenter.Content> </ContentPresenter> <ComboBox ItemsSource="{Binding Path=Types}" x:Name="filterComboBox" VerticalAlignment="Center" HorizontalAlignment="Right" MinWidth="20" Height="Auto" OpacityMask="Black" Visibility="Collapsed" Text="" Grid.Column="0" Grid.ColumnSpan="1"/> </Grid> </my:DataGridHeaderBorder> <ControlTemplate.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Trigger.EnterActions> <BeginStoryboard x:Name="ShowFilterControl_BeginStoryboard" Storyboard="{StaticResource ShowFilterControl}"/> <StopStoryboard BeginStoryboardName="HideFilterControl_BeginShowFilterControl"/> </Trigger.EnterActions> <Trigger.ExitActions> <BeginStoryboard x:Name="HideFilterControl_BeginShowFilterControl" Storyboard="{StaticResource HideFilterControl}"/> <StopStoryboard BeginStoryboardName="ShowFilterControl_BeginStoryboard"/> </Trigger.ExitActions> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> <Setter Property="Background"> <Setter.Value> <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"> <GradientStop Color="#FF0067AD" Offset="1"/> <GradientStop Color="#FF003355" Offset="0.5"/> <GradientStop Color="#FF78A8C9" Offset="0"/> </LinearGradientBrush> </Setter.Value> </Setter> <Setter Property="Foreground" Value="White"/> <Setter Property="BorderBrush"> <Setter.Value> <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"> <GradientStop Color="#D8000000" Offset="0.664"/> <GradientStop Color="#7F003355" Offset="1"/> </LinearGradientBrush> </Setter.Value> </Setter> <Setter Property="FontWeight" Value="Bold"/> <Setter Property="BorderThickness" Value="1,1,1,0"/> <Setter Property="HorizontalContentAlignment" Value="Center"/> <Setter Property="Padding" Value="5,0"/> </Style> As you can see, I'm trying to databind the combobox's ItemsSource to Types, but this doesn't work. The list is in my ViewModel that is being applied to my page, how would I specify in this style that is in my resource dictionary that I want to bind to a source in my viewmodel.

    Read the article

  • WPF Data Binding won't work

    - by Tokk
    Hey, I have got an UserControll with a DependencyProperty called "Risikobewertung" whitch has the own Datatype "RisikoBewertung"(Datatype created by LINQ). So in my Controll I try to bind the Fields of RisikoBewertung to the TextBoxes on the Controll, but It won't work. I hope you can help me, and tell me why ;) Code: UserControl.xaml: <UserControl x:Class="Cis.Modules.RiskManagement.Views.Controls.RisikoBewertungEditor" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:gridtools="clr-namespace:TmgUnity.Common.Presentation.Controls.DataGridTools;assembly=TmgUnity.Common.Presentation" xmlns:converter="clr-namespace:Cis.Modules.RiskManagement.Views.Converter" xmlns:tmg="clr-namespace:TmgUnity.Common.Presentation.Controls.FilterDataGrid;assembly=TmgUnity.Common.Presentation" xmlns:validators="clr-namespace:TmgUnity.Common.Presentation.ValidationRules;assembly=TmgUnity.Common.Presentation" xmlns:toolkit="http://schemas.microsoft.com/wpf/2008/toolkit" xmlns:risikoControls="clr-namespace:Cis.Modules.RiskManagement.Views.Controls"> <UserControl.Resources> <converter:CountToArrowConverter x:Key="CountConverter" /> </UserControl.Resources> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Name="Veränderung"/> <ColumnDefinition Name="Volumen" /> <ColumnDefinition Name="Schadenshöhe" /> <ColumnDefinition Name="SchadensOrte" /> <ColumnDefinition Name="Wahrscheinlichkeit" /> <ColumnDefinition Name="Kategorie" /> <ColumnDefinition Name="Handlungsbedarf" /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="20" /> <RowDefinition /> </Grid.RowDefinitions> <Image Source="{Binding Path=Entwicklung, Converter={StaticResource CountConverter}, UpdateSourceTrigger=PropertyChanged}" Grid.RowSpan="2" Grid.Row="0" Width="68" Height="68" Grid.Column="0" /> <TextBox Grid.Column="1" Grid.Row="0" Text="Volumen" /> <TextBox Grid.Column="1" Grid.Row="1"> <TextBox.Text> <Binding Path="Volumen" UpdateSourceTrigger="PropertyChanged" /> </TextBox.Text> </TextBox> <TextBox Grid.Column="2" Grid.Row="0" Text="Schadenshöhe" /> <TextBox Grid.Column="2" Grid.Row="1" Text="{Binding Path=Schadenshöhe, UpdateSourceTrigger=PropertyChanged}" /> <StackPanel Grid.Column="3" Grid.RowSpan="2" Grid.Row="0" Orientation="Horizontal"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="20" /> <RowDefinition /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition /> <ColumnDefinition /> </Grid.ColumnDefinitions> <TextBox Text ="Politik" Grid.Row="0" Grid.Column="0"/> <CheckBox Name="Politik" Grid.Row="1" Grid.Column="0" IsChecked="{Binding Path=Politik, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Center" HorizontalAlignment="Center" /> <TextBox Text ="Vermögen" Grid.Row="0" Grid.Column="1" /> <CheckBox Name="Vermögen" Grid.Row="1" Grid.Column="1" IsChecked="{Binding Path=Vermögen, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Center" HorizontalAlignment="Center" /> <TextBox Text ="Vertrauen" Grid.Row="0" Grid.Column="2" /> <CheckBox Name="Vertrauen" Grid.Row="1" Grid.Column="2" IsChecked="{Binding Path=Vertrauen, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Center" HorizontalAlignment="Center" /> </Grid> </StackPanel> <TextBox Grid.Column="4" Grid.Row="0" Text="Wahrscheinlichkeit" /> <TextBox Grid.Column="4" Grid.Row="1" Text="{Binding Path=Wahrscheinlichkeit, UpdateSourceTrigger=PropertyChanged}"/> <risikoControls:RiskTrafficLightControl Grid.Column="5" Grid.Row="0" Grid.RowSpan="2" RiskValue="{Binding Path=Kategorie, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" /> <StackPanel Grid.Column="6" Grid.RowSpan="2" Grid.Row="0" Orientation="Vertical"> <TextBox Text="Handlungsbedarf" /> <CheckBox VerticalAlignment="Center" HorizontalAlignment="Center" IsChecked="{Binding Path=Handlungsbedarf, UpdateSourceTrigger=PropertyChanged}" /> </StackPanel> </Grid> The CodeBehind: 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.ComponentModel; using Cis.Modules.RiskManagement.Data; using Cis.Modules.RiskManagement.Views.Models; namespace Cis.Modules.RiskManagement.Views.Controls { /// <summary> /// Interaktionslogik für RisikoBewertungEditor.xaml /// </summary> public partial class RisikoBewertungEditor : UserControl, INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public static readonly DependencyProperty RisikoBewertungProperty = DependencyProperty.Register("RisikoBewertung", typeof(RisikoBewertung), typeof(RisikoBewertungEditor), new PropertyMetadata(null, new PropertyChangedCallback(RisikoBewertungChanged))); // public static readonly DependencyProperty Readonly = DependencyProperty.Register("EditorReadonly", typeof(Boolean), typeof(RisikoBewertungEditor), new PropertyMetadata(null, new PropertyChangedCallback(ReadonlyChanged))); private static void RisikoBewertungChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs arguments) { var bewertungEditor = dependencyObject as RisikoBewertungEditor; bewertungEditor.RisikoBewertung = arguments.NewValue as RisikoBewertung; } /* private static void ReadonlyChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs arguments) { } */ public RisikoBewertung RisikoBewertung { get { return GetValue(RisikoBewertungProperty) as RisikoBewertung; } set { SetValue(RisikoBewertungProperty, value); if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("RisikoBewertung")); } } } /* public Boolean EditorReadonly { get; set; } */ public void mebosho(object sender, RoutedEventArgs e) { MessageBox.Show(RisikoBewertung.LfdNr.ToString()); } public RisikoBewertungEditor() { InitializeComponent(); RisikoBewertung = new RisikoBewertung(); this.DataContext = (GetValue(RisikoBewertungProperty) as RisikoBewertung); } } } and a little example of it's usage: <tmg:FilterDataGrid Grid.Row="0" AutoGenerateColumns="False" ItemsSource="{Binding TodoListe}" IsReadOnly="False" x:Name="TodoListeDataGrid" CanUserAddRows="False" SelectionUnit="FullRow" SelectedValuePath="." SelectedValue="{Binding CurrentTodoItem}" gridtools:DataGridStyle.SelectAllButtonTemplate="{DynamicResource CisSelectAllButtonTemplate}" CanUserResizeColumns="True" MinHeight="80" SelectionChanged="SelectionChanged" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" diagnostics:PresentationTraceSources.TraceLevel="High" > <tmg:FilterDataGrid.RowDetailsTemplate> <DataTemplate> <risikoControls:RisikoBewertungEditor x:Name="BewertungEditor" RisikoBewertung="{Binding ElementName=TodoListeDataGrid, Path=SelectedValue}" diagnostics:PresentationTraceSources.TraceLevel="High"> </risikoControls:RisikoBewertungEditor> </DataTemplate> </tmg:FilterDataGrid.RowDetailsTemplate> <tmg:FilterDataGrid.Columns> <toolkit:DataGridTextColumn Binding="{Binding Path=LfdNr}" Header="LfdNr" /> </tmg:FilterDataGrid.Columns> </tmg:FilterDataGrid>

    Read the article

< Previous Page | 1 2 3 4