Quantcast
Channel: Windows Presentation Foundation (WPF) forum
Viewing all 18858 articles
Browse latest View live

Add Label To WPF user Control

$
0
0

am using some example code for Windows 7 to have an application manipulate images. What I'd like to do is add a label to the bottom of the image. The program generates images on the fly. Here is a portion of the picture control:

publicpartialclassPicture:UserControl{publicLabel label;publicPicture(){InitializeComponent();DataContext=this;
        label =newLabel();}publicstringImagePath{
        get {return(string)GetValue(ImagePathProperty);}set{SetValue(ImagePathProperty, value);}}}

and this is the code that creates the picture:

Picture p =newPicture();
 p.ImagePath= path.ToString();
 p.label.Content= p.ImagePath;

This is not working for me because it doesn't really create a label where I can set text on it. Am I going about this wrong?

I am using the code from the Windows7TrainingKit called "Multitouch - Managed"


Help to convert sample WPF--EF project to MVVM pattern

$
0
0

This project contains two comboboxes, one textbox, one ADO.Net Entity Model (with two tables), and a little less than 50 lines of code (including the using directives) in the MainWindow.xaml.cs file (code behind MainWindow -- VS2012 -- win7 -- source code below).  The two tables are named Authors (the master table -- 3 rows) and Books (the detail table -- 6 rows) and the tables are constrained (related) by PK-FK.  On project startup Combo1 gets populated by all the rows (3 rows) from the Authors table and displays the first row (first author ordered asc), and simultaneously combo2 gets populated with the corresponding books (detail) rows for the author being displayed/selected in Combo1, and Combo2 displays the first book (ordered asc), and the textbox displays the description of the book being displayed in Combo2.  If another author is selected in Combo1 then the content of Combo2 changes to the corresponding book(s) for that author, and the book displayed in Combo2 changes to the first book for the selected author (books also ordered asc), and the description in the textbox changes to the currently selected row in Combo2.

I want to keep the same functionality/operation in this project -- except using the MVVM pattern.  I am "guessing" that the model would most likely consist of two observableCollection objects where the first observableCollection object would contain all the rows in the Authors table, and the 2nd observableCollection object would contain the corresponding row(s) from the Books table.  Then I am "guessing" that the viewmodel would contain three properties for populating the two comboboxes and the textbox. 

Where I start losing understanding (of the MVVM pattern) is that I don't quite know the rules when I need to use an ICommand command.  Can I achieve the same functionality/operation as the original (non-mvvm) WPF project with just properties (and the propertyChanged event)?  Or will ICommand be required somewhere since there are click actions in the comboboxes?  I am hoping someone could clarify the rules here (and set me straight if I am on the right or wrong track thinking about observable collections in the model ...), and I would be very greatful if someone coul demostrate some code samples for the model and view model for this project (like will I need to implement INotifyPropertyChanged in the model?).  Oh, would the xaml have to be modified also (besides the bindings) to function with MVVM?

First I create the two tables (Authors and Books) in a sql server database (of any choosing on like sql express).  Here is the Tsql for that

create table Author (AuthorId int primary key, AuthorName nvarchar(50))
create table Book (BookId int primary key, AuthorId int, Title nvarchar(50), Description nvarchar(200), Price money)
alter table Book add constraint FK_Book_Author foreign key (AuthorId) references Author (AuthorId)

insert into Author values (1, 'Gambardella, Matthew')
insert into Author values (2, 'Ralls, Kim')
insert into Author values (3, 'Corets, Eva')

insert into Book values (1, 1, 'XML Developers Guide', 'An in-depth look at creating applications with XML.', 4.95)
insert into Book values (2, 1, 'Foods of the world.', 'Simply a book about food.',  5.95)
insert into Book values (3, 1, 'Cars', 'A book about cars.',  8.95)
insert into Book values (4, 2, 'Scarecrows', 'This be could horror or agriculture.', 4.15)
insert into Book values (5, 3, 'Book of blue', 'First in a series of books about colors',  6.30)
insert into Book values (6, 3, 'EF', 'Some tips and trics on Entity Frameworks',  3.45)

Then I create a blank WPF project and add an ADO.Net Entity Model which I name Bookshop.edmx (using EF5 -- or EF6 works also).  The context I named BookshopEntities, then I select Authors and Books from the Entities Model wizard and save the model as BookshopModel.

Here is the xaml for MainWindow.xaml

<Window x:Class="myWPF_EFsample.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 Width="180" /><ColumnDefinition Width="*" /></Grid.ColumnDefinitions><Grid.RowDefinitions><RowDefinition Height="25" /><RowDefinition Height="*" /></Grid.RowDefinitions><ComboBox DisplayMemberPath="AuthorName" ItemsSource="{Binding}" IsSynchronizedWithCurrentItem="true"
                      Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="1" Name="cbAuthors" SelectionChanged="cbAuthors_SelectionChanged" /><ComboBox DisplayMemberPath="Title" ItemsSource="{Binding}" IsSynchronizedWithCurrentItem="true"
                      Grid.Row="0" Grid.Column="1" Grid.ColumnSpan="1" Name="cbBooks" SelectionChanged="cbBooks_SelectionChanged" /><TextBlock Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2" Name="tbDesc"/></Grid></Window>

and here is the code in MainWindow.xaml.cs (the MainWindow code behind)

using System.Linq;
using System.Windows;
using System.Windows.Controls;

namespace myWPF_EFsample
{
    public partial class MainWindow : Window
    {
        BookshopEntities ctx = new BookshopEntities();
        public MainWindow()
        {
            InitializeComponent();
            FillAuthors();
        }

        private void FillAuthors()
        {
            var q = (from a in ctx.Authors select a).ToList();
            cbAuthors.DataContext = q;
        }

        private void FillBook()
        {
            Author author = (Author)cbAuthors.SelectedItem;

            var q = (from book in ctx.Books
                     orderby book.Title
                     where book.AuthorId == author.AuthorId
                     select book).ToList();

            cbBooks.DataContext = q;
        }

        private void FillDescription()
        {
            Book book = (Book)cbBooks.SelectedItem;
            tbDesc.Text = book.Description;
        }

        private void cbAuthors_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            FillBook();
        }

        private void cbBooks_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            FillDescription();
        }
    }
}
Any suggestions or examples how to set up the Model and ViewModel would be greatly appreciated -- and if I will need a RelayCommand class.


Rich P


Accordion with summary

$
0
0

Hi, i would like to design an accordion component with WPF, but the problem is that the collapsed accordion state should contain a summary of data.

Can any one help?

TabItem templating with overlap

$
0
0

Hi,

I'd like to template a WPF TabControl, in order to display tabitems headers like that :

------------------------

\                             \

/______________/

The shape looks like an arrow (like a > extruded, or the icon of "fast forward" filled), and each arrow represents a step in a process. A content presenter is displayed inside the arrow to indicate the step name.

The point is, I'd like each arrow to fit to the next (with one or two pixels between them). But all templating I can see for tabcontrols keep the rectangular shape of the container. I tried to use sample grids with negative margins, but the arrow is cropped.

Please could someone give me a small example of this ? The standard ControlTemplate I get from MS site uses a TabPanel, which I cannot avoid if I want to keep the TabControl headers behavior.

Thank you in advance. 

Change the Background color of Rectangel area of WPF Ribbon tab

$
0
0

Hi,

How can we change the background color of the rectangle region of WPF Ribbon Tab, its not working if we apply background color for ribbon group, only ribbon group area is getting filled leaving the remaining area with default color. 

Please help me on this.

Thanks. 

Programatically close current window and open new window

$
0
0

hi,

I am in a click event of a button and want to close the current window and open a new window if a condition is met.

   else if(MyText.Content=="OpenNew")
                {
                newwindow sw = new newwindow();
                sw.Dispatcher.Invoke(new Action(() => sw.Show()));
                this.Dispatcher.Invoke(new Action(() => this.Close()));
                }

But I always get the System.InvalidOperationException.

Pls help me with this.

Thanks,

Shaleen



TheHexLord

Datagrid SelectedItems in MVVM

$
0
0

Hi,

I have written the following for retrieving the datagrid selecteditems, which is a readonly property .

namespace Wpf.Behaviours
{
    using System.Collections;
    using System.Windows;
    using System.Windows.Controls;

    public static class DataGridSelectedItems
    {

        public static readonly DependencyProperty SelectedItemsProperty = DependencyProperty.RegisterAttached("SelectedItems", typeof(IList), typeof(DataGridSelectedItems), new PropertyMetadata(OnSelectionChanged));

      
        #region SelectedItems

        public static void SetSelectedItems(DependencyObject frameworkElement, IList value)
        {
            frameworkElement.SetValue(SelectedItemsProperty, value);
        }

        public static IList GetSelectedItems(DependencyObject frameworkElement)
        {
            return (IList)frameworkElement.GetValue(SelectedItemsProperty);
        }

        #endregion

        private static void OnSelectionChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
        {
            var datagrid = (DataGrid)dependencyObject;

            if ((bool)e.NewValue)
            {
                datagrid.SelectionChanged += new SelectionChangedEventHandler(datagrid_SelectionChanged);
            }
            else
            {
                datagrid.SelectionChanged -= datagrid_SelectionChanged;
            }
        }

        private static void datagrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var datagrid = sender as DataGrid;
            UpdateSelection(datagrid);
        }

        private static void UpdateSelection(DataGrid datagrid)
        {
            if (datagrid != null)
            {
                datagrid.SetCurrentValue(SelectedItemsProperty, datagrid.SelectedItems);
            }
        }
    }
}

Binding in xaml is as follows

<Datagrid 

Behaviours:DataGridSelectedItems.SelectedItems="{Binding SelectedItems, Mode=OneWayToSource}"/>

The selecteditems property setter is being called only once and that too on startup, its not getting called on selection change. May someone help me by correcting my code.

Thanking you

Ramakrishna


Ramakrishna




ErrorTemplate on editing datagrid

$
0
0

Hello,

I'm trying to create a MVVM application to register purchases.

I have ViewModel composed by :

  • Purchase
  • Products (return collection of products of the Purchase(Purchase.products)
  • ProductToAdd (this is a product to add to the Purchase via button)
  • Implement IDataErrorInfo to validate the order and the products collection

I created a collection of error to validate the ProductToAdd on button click.

So if there is an error on ProductToAdd the product is not add to the collection and the textbox with error become Red.

The value of each product of the purchase can be updated in the datagrid.

My problem is : When i update value in DataGrid the cell updated didn't get errorTemplate when is there an error.

My sample is the following : http://www.filedropper.com/validationexample_3

I didn't know how can i do 2 type of validation.

thanks


How to use a generic type on a behavior?

$
0
0

I would like to use a behavior to bind the selected items of a datagrid. I find this solution:

https://social.msdn.microsoft.com/Forums/en-US/5041c158-e48b-4efd-9f73-848a85abba83/datagrid-selecteditems-in-mvvm?forum=wpf

But I have various problems.

public static readonly DependencyProperty SelectedItemProperty =
        DependencyProperty.Register("SelectedItems", typeof(IList<object>),
        typeof(DataGridSelectedItemsBlendBehavior),
        new FrameworkPropertyMetadata(null)
        {
          BindsTwoWayByDefault = true
        });

In this code, it is used a IList<object>, this allows to reuse the behavior for any type, but this makes me that in my view model, my SelectedItems must be ObservableCollection<object> instead of ObservableCollection<MyCustomObjefct>. If the type is not the same in the behavior and in the view model, the collection in my view model is never updated. If the two types are the same, them (object or myCustomObject), then the collection in my view model is updated. But if I use MyCustomObject type, I can't reuse the behavior.

So the option is to use a ObservableCollection<object>() on my view model, but this is another problem, because when I need to access to the information of one element, I need to do a cast:

((MyCustomObject)SelectedItems[0]).MyProperty

So there is so tedious work and the code is harder to read, and I have to do a cast, that I guess that always has a cost.

Despite of using an object as type, I can use the dynamic type, but I need to do the cast if I want to use linq, so I have the same problem.

I also try to create a behavior that use a generic type, something like this:

public class DatagridSelectedItemsBehavior<T> : Behavior<DataGrid>

But with this solution, the view can't see the behavior, so I can't use the behavior with the view.

There is any solution for this problem or I need to do the cast if I want to reuse the behavior?

Thank so much.

Delay between Canvas

$
0
0
Canvas appear on the window after few second delay. i am doing in such way
Canvas1.Background = System.Windows.Media.Brushes.Red;
Canvas2.Background = System.Windows.Media.Brushes.OrangeRed;
Canvas3.Background = System.Windows.Media.Brushes.Yellow;
Canvas2 take 5 seconds then display on screen after canvas1. and same case scene with canvas3. Can someone tell me how i can do in wpf? waiting for your feedback

How can I set a property when an event happens? (selection changed on datagrid)

$
0
0

I have a datagrid, I would like to change the backgrund of the datagrid when the selection changed event is fired.

I can not use data trigger, because is in the case that I expected a value, but in this case is when change, to any value.

An option is to use an event trigger, but all the examples that I have found is to use with an actions, and I just want to set a property.

How could I do that?

I am using MVVM pattern, so I would like to avoid the use in code-behind.

Thank so much.

Change Row and Add new row on Datagrid using MVVM

$
0
0

Below is my Xaml and ViewModel class looks like. I try to change the existing row or add new row but both of them doesnt work. When I click empty row, it looses the focus. how I can achieve it directly on Xaml or in ViewModel without using code behind?

<UserControl x:Class="ucCustomer"
         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"
         xmlns:myWPF="clr-namespace:myWPF"
         xmlns:vm="clr-namespace:myWPF.ViewModels"
         mc:Ignorable="d"
       MinWidth="750" MinHeight="650" ><Grid><Grid.DataContext><vm:CustomerVM /></Grid.DataContext><Button x:Name="btnSave" Margin="0,10,10,0" Width="120" Height="25" Content="Save Changes" Command="{Binding btnClick}" HorizontalAlignment="Right" VerticalAlignment="Top"/><DataGrid x:Name="grdData"  AutoGenerateColumns="False" Margin="10,50,10,5"   Style="{StaticResource myDataGrid}"
                  ItemsSource="{Binding Customers, Mode=TwoWay}"><DataGrid.Columns><DataGridTextColumn Header="CustomerId"    Binding="{Binding Path=CustomerId}" Width="50"></DataGridTextColumn><DataGridTextColumn Header="CustomerName" Binding="{Binding Path=CustomerName}" Width="150"></DataGridTextColumn><DataGridTextColumn Header="AccountId"  Binding="{Binding Path=AccountId}" Width="130"></DataGridTextColumn><DataGridTextColumn Header="AccountName"   Binding="{Binding Path=AccountName}" Width="200"></DataGridTextColumn><DataGridTextColumn Header="ModifyDate" IsReadOnly="True"  Binding="{Binding Path=ModifyDate}" Width="130"></DataGridTextColumn></DataGrid.Columns></DataGrid></Grid>

   Namespace ViewModels
            Public Class CustomerVM
                Inherits BaseViewModel
                Implements ICustomerVM

                Private _Customer

    s As New ObservableCollection(Of Models.Customer)
            Private mySaveCommand As ICommand
            Private myLoadCommand As ICommand

            Public Sub New()
                mySaveCommand = New Commands.SaveCustomers(Me)
                myLoadCommand = New Commands.LoadCustomer()
                _Customers = GetCustomers()
            End Sub


            Public Property Customers() As ObservableCollection(Of Models.Customer)
                Get
                    Return _Customers
                End Get
                Set(value As ObservableCollection(Of Models.Customer))
                    _Customers = value
                End Set
            End Property

            Public ReadOnly Property btnClick() As ICommand
                Get
                    Return mySaveCommand
                End Get
            End Property



            Function GetCustomers() As ObservableCollection(Of Models.Customer) Implements ICustomerVM.GetCustomer


                If _Customers Is Nothing OrElse _Customers.Count = 0 Then myLoadCommand.Execute(_Customers)

                Return _Customers
            End Function


            Public Function SaveCustomerstoDB() As Integer
                Dim myContext As New Models.myModelContext
                Return myContext.SaveChanges()
            End Function


        End Class
    End Namespace


    Namespace ViewModels
    Public Class BaseViewModel
        Implements INotifyPropertyChanged

        Public Event PropertyChanged(sender As Object, e As PropertyChangedEventArgs) Implements INotifyPropertyChanged.PropertyChanged
        Protected Sub OnPropertyChanged(propertyName As String)
            RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
        End Sub

        Protected Sub SetAndNotify(Of T)(ByRef field As T, value As T, propertyName As String)
            If Not EqualityComparer(Of T).[Default].Equals(field, value) Then
                field = value
                OnPropertyChanged(propertyName)
            End If
        End Sub

    End Class
End Namespace


"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it."

Reading a Text (.log) File

$
0
0

I am writing a WPF application using C# and find I need to read a text file.  The method to read the file is not that complicated in itself, but how I need to read it escapes me.

Every line in this log file begins with a timestamp in the 'yyyy=MM-dd HH:mm:ss.ffff' format (2015-01-12 14:02:15.2145).  This log file is a record of everything a third party application does such as Startup time, synchronization status, ticket scan status and shutdown time.  It is the ticket scan status line in need to read.  These lines end with Scan Result:  <result>.

My logic runs this way:

  • Click button - record DateTime.Now as a string in the same format as above (yyyy-MM-dd HH:mm:ss.ffff) then call the third party application (calling the application is not a problem)
  • Search for lines in log file (2015-01-12.log) which contain the text "Scan Result: Valid Ticket"
  • Check this line to make sure the timestamp of this line is greater than the time recorded when button was clicked
  • Increase an int variable by one for each line it finds as a Valid Ticket (ticketcount++)

I have no code to post at this point since my mind has drawn a complete blank on how to proceed.

Thank you.

System.OutOfMemoryException in WPF code ...

$
0
0

Hi,

I do have the following WPF code written in C#:

public Bitmap BitmapImage2Bitmap(BitmapImage bitmapImage)
{
    try
    {
       using (MemoryStream stream = new MemoryStream())
       {
            BitmapEncoder enc = new BmpBitmapEncoder();
            enc.Frames.Add(BitmapFrame.Create(bitmapImage));
            enc.Save(stream); // System.OutOfMemory Exception
            System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(stream);
            return new Bitmap(bitmap);
       }
    }
    catch (Exception ex)
    {
       MessageBox.Show(ex.Message);
    }
    return null;
}

public BitmapImage Convert2BitmapImage(object value)
{
    try
    {
        if (value != null && value is byte[])
        {
           var bytes = value as byte[];
           var stream = new MemoryStream(bytes);
           var image = new BitmapImage();
           image.BeginInit();
           image.StreamSource = stream;
           image.EndInit();
           return image;
        }
    }
    catch (Exception ex)
    {
       MessageBox.Show(ex.Message);
    }
    return null;
}

Basically, I am getting Byte[] from DB. I am creating a Bitmap from that. Can you provide some pointers on this to resolve this issue ?

USAGE:

Bitmap bmp = BitmapImage2Bitmap(Convert2BitmapImage(Byte[]));

Raise Key pressed event

$
0
0

Hello, any know how can I raise a key press event throw code. For example I want to simulate that the user has press the A Key. How can I do that throw code?

 

Thanks a lot !!


Is WPF the worst mistake in development technology Microsoft has ever made? Is WCF the best development technology Microsoft has ever made?

$
0
0

·        Clearly, my point of view is yes on both counts.

WPF is the worst, largest scale mistake in development technology Microsoft has ever made

WCF is the best development technology Microsoft has ever made

I believe that WPF shows a lack of integrity as it is a waste of time, money and effort for the development community and technology consumers world wide.  My reasoning is that Microsoft owns the desktop development platform there is no reason for a regression to a mark up language when the WYSIWYG forms platform was high productivity technology.  Mark up language development from Microsoft should have been left in the Web domain.  I personally have worked for 10 years on very large web sites hand coding mark up language - there was no need for this regression back to almost Mainframe like coding tools on the desktop platform which Microsoft owns.

I believe that this move was regressive, not in the best interests of Microsoft, nor the Microsoft developer community and certainly WPF was not a technology decision of integrity and has not brought productivity improvements for clients.

I would like to start a discussion on this and put it out there in the public domain for sensible and mature consideration by experienced developers with preferably 15+ years experience across multiple platforms and technologies.  My personal experience is 20 years starting on Unix C, then VB, Sybase, MSQL, Unix, ASP, ASP.NET, VB.NET, C#, Java, Winforms, WPF, AJAX, MTS, COM, DCOM, Web Services, WCF, SharePoint, BizTalk, Dynamics, MSCRM....

 

Viewing map problem in wpf

$
0
0

Hi There;

I try to implement the solution described in Arcgis runtime sdk for .net. I try to implement ArcGISDynamicMapServiceLayer in the code examples. Here is the xaml code:

<Window x:Class="ArcGISDynamicMapServiceLayer.MainWindow"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:esri="http://schemas.esri.com/arcgis/runtime/2013"
             Height="600" Width="800"><Grid><!-- Add a MapView Control to the application. --><esri:MapView><!-- Add a Map. --><esri:Map><!-- Add an ArcGISDynamicMapServiceLayer via XAML. --><esri:ArcGISDynamicMapServiceLayer ID="World Time Zones"
                      ServiceUri="http://sampleserver6.arcgisonline.com/arcgis/rest/services/WorldTimeZones/MapServer"/></esri:Map></esri:MapView></Grid></Window>

Whenever I run this code in my machine, a window appears; however there is no map at all. What is the problem and how can I solve it?

Thanks in advance.

Problem loading a dll

$
0
0

I have an application needing IALoader.dll to make ink analysis. I use IACore.dll, IAWinFX.dll, Microsoft.Ink.Analysis.dll.  This application is lunched automatically. I have IALoader.dll added as reference with Copy local=true. In the config i have:

<startup useLegacyV2RuntimeActivationPolicy="true"><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0" /></startup><runtime><assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1" appliesTo="v1.0.3705"><dependentAssembly><assemblyIdentity name="IALoader" publicKeyToken="31bf3856ad364e35" culture="neutral" /></dependentAssembly><dependentAssembly><assemblyIdentity name="IACore" publicKeyToken="31bf3856ad364e35" culture="neutral" /></dependentAssembly><dependentAssembly><assemblyIdentity name="IAWinFX" publicKeyToken="31bf3856ad364e35" culture="neutral" /></dependentAssembly><dependentAssembly><assemblyIdentity name="Microsoft.Ink.Analysis" publicKeyToken="31bf3856ad364e35" culture="neutral" /></dependentAssembly></assemblyBinding></runtime>

While i debug on visual studio 2010.... it works very well but once i used it outside it (even adding all those dll in the same directory)it doesnt work.. cause IT DOESNOT LOAD IALoader.dll, and an error is thrown:

The assembly mix mode is compiled against runtime V 1.0.3705  and is not possible to load in runtime V4.0 without additional configuration

Any one can help???

Thanksss

WPF custom ComboBox : How to make the text part clickable

$
0
0

Hi,

I have this code for my WPF custom combo box:

<Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ComboBox">
                    <Grid>
                        <ToggleButton Name="ToggleButton" Template="{DynamicResource ComboBoxToggleButton}"
                            Grid.Column="2" Focusable="false"
                            IsChecked="{Binding Path=IsDropDownOpen,Mode=TwoWay,RelativeSource={RelativeSource TemplatedParent}}"
                            ClickMode="Press">
                        </ToggleButton>

                        <ContentPresenter Name="ContentSite" IsHitTestVisible="False" Content="{TemplateBinding SelectionBoxItem}"
                            ContentTemplate="{TemplateBinding SelectionBoxItemTemplate}"
                            ContentTemplateSelector="{TemplateBinding ItemTemplateSelector}" VerticalAlignment="Center"/>

                        <Border BorderThickness="1,1,1,1" Margin="-10,0,-5,0"  BorderBrush="#d2d4d5" CornerRadius="3" />

                       
                        <Popup Name="Popup" Placement="Bottom" IsOpen="{TemplateBinding IsDropDownOpen}"
                            AllowsTransparency="True" Focusable="False" PopupAnimation="Slide" Opacity="1">
                            <Grid  Name="DropDown" SnapsToDevicePixels="True" MinWidth="{TemplateBinding ActualWidth}"
                                MaxHeight="{TemplateBinding MaxDropDownHeight}">
                                <Border  x:Name="DropDownBorder" Background="White" BorderThickness="1"  BorderBrush="#d2d4d5" Opacity="1"/>
                                <ScrollViewer Margin="4,6,4,6" SnapsToDevicePixels="True">
                                    <StackPanel IsItemsHost="True" KeyboardNavigation.DirectionalNavigation="Contained" />
                                </ScrollViewer>
                            </Grid>
                        </Popup>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>

But with this code, I am able to click only on the toggle button part of the combo box  to make the pop-up visible.But I want to be able to click on the content presenter part and make the popup visible as well. How can i do that,please suggest.

Regards,

Samjukta

How to select multiple checkboxes in a same row.

$
0
0

Hello,

I am creating a DataGrid in wpf and its columns are dynamic i.e from code behind, first column is name column and the rest are coming from the "Shift" table i.e all rows in "Shift table" are display as a columns , and CheckBoxes in a row. Issue comes up when i check a checkbox in a row, all checkboxes get selected automatically in that particular row. Can anybody please help?

My Code is as Follows : Xaml

<DataGrid Margin="0,55,0,0" AutoGenerateColumns="False" CanUserAddRows="False"   HorizontalAlignment="Left"  Name="gdVolunteerShift" VerticalAlignment="Top"  MouseDoubleClick="gdUser_MouseDoubleClick" RowEditEnding="gdVolunteerShift_RowEditEnding" FrozenColumnCount="1" >
            <DataGrid.Columns>
            </DataGrid.Columns>
        </DataGrid>

.CS part

var volenteersShift = volenteerService.GetAllVolunteerShifts();
                if (Guid.Empty != VolenteerID)
                    volenteersList = volenteersList.Where(q => q.Related_Volenteer == this.VolenteerID).ToList();
                var shifts = volenteersShift.Select(c => c.Shift_Master.Name).Distinct().ToList();

Binding ChkBind = new Binding("Show_Up");
                ChkBind.Mode = BindingMode.TwoWay;

                ChkBind.NotifyOnTargetUpdated = true;
                ChkBind.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
                
                FirstFloor.ModernUI.Windows.Controls.DataGridTextColumn VolColumnname = new FirstFloor.ModernUI.Windows.Controls.DataGridTextColumn();
                VolColumnname.Header = "Volunteer Name";
                VolColumnname.Binding = new Binding("VolenteerItem.FullName");
                gdVolunteerShift.Columns.Add(VolColumnname);
               
                FirstFloor.ModernUI.Windows.Controls.DataGridCheckBoxColumn[] chk1 = new FirstFloor.ModernUI.Windows.Controls.DataGridCheckBoxColumn[shifts.Count()];
                foreach (var col in shifts.Select((value, index) => new { Value = value, Index = index }))
                {
                    chk1[col.Index] = new FirstFloor.ModernUI.Windows.Controls.DataGridCheckBoxColumn();
                    
                    chk1[col.Index].IsThreeState = true;
                    
                    
                    var newTextBlock = new FrameworkElementFactory(typeof(TextBlock));
                    
                    newTextBlock.SetValue(TextBlock.TextProperty, col.Value.ToString());
                    newTextBlock.SetValue(TextBlock.LayoutTransformProperty, new RotateTransform(-90));
                    DataTemplate newDataTemplate = new DataTemplate() { VisualTree = newTextBlock };
                    
                    chk1[col.Index].HeaderTemplate = newDataTemplate;
                    chk1[col.Index].Binding = ChkBind;
                    
                    gdVolunteerShift.Columns.Add(chk1[col.Index]);
                }
                


                gdVolunteerShift.ItemsSource = volenteersList;



Viewing all 18858 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>