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

WPF use Multi-thread question

$
0
0

I want save all UserControl as image, at the same time, I need to show a animation in order to make the UI better for users.

This is MainWindow:

<Window x:Class="WPF.MainWindow"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
         xmlns:local="clr-namespace:FluidV.Components"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:vw="http://inosoft.com/visiwin7"
         d:DesignHeight="100"
         d:DesignWidth="1024"
         mc:Ignorable="d"><Grid x:Name="LayoutRoot"><Button Margin="10" Click="Button1_click"/></Grid></Window>

This is UserControl:

<UserControl x:Class="WPF.AnimationView"
         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"
         Opacity="0.6"
         Background="#A8007499"
         mc:Ignorable="d"
         d:DesignHeight="300"
         d:DesignWidth="300"><Grid><DataGrid Name="dataGrid1"
                  Width="441"
                  Height="99"
                  Margin="40,70,0,0"
                  HorizontalAlignment="Left"
                  VerticalAlignment="Top"
                  AutoGenerateColumns="False" /><Canvas Name="loading"
                Width="120"
                Height="120"
                Margin="187,76,241,85"
                HorizontalAlignment="Center"
                VerticalAlignment="Center"
                RenderTransformOrigin="0.5,0.5"><Ellipse Canvas.Left="55"
                     Canvas.Top="31"
                     Width="15"
                     Height="15"
                     Fill="#FFD1D1F7"
                     Opacity="1.0"
                     Stretch="Fill" /><Ellipse Canvas.Left="38"
                     Canvas.Top="39"
                     Width="15"
                     Height="15"
                     Fill="Blue"
                     Opacity="0.8"
                     Stretch="Fill" /><Ellipse Canvas.Left="36"
                     Canvas.Top="58"
                     Width="15"
                     Height="15"
                     Fill="#FF0000FE"
                     Opacity="0.7"
                     Stretch="Fill" /><Ellipse Canvas.Left="52"
                     Canvas.Top="67"
                     Width="15"
                     Height="15"
                     Fill="Blue"
                     Opacity="0.6"
                     Stretch="Fill" /><Ellipse Canvas.Left="68"
                     Canvas.Top="61"
                     Width="15"
                     Height="15"
                     Fill="#FF2E2EFF"
                     Opacity="0.5"
                     Stretch="Fill" /><Ellipse Canvas.Left="69"
                     Canvas.Top="42"
                     Width="15"
                     Height="15"
                     Fill="#FF6F6FFF"
                     Opacity="0.4"
                     Stretch="Fill" /><Canvas.RenderTransform><RotateTransform x:Name="SpinnerRotate"
                                 Angle="0" /></Canvas.RenderTransform><Canvas.Triggers><EventTrigger RoutedEvent="ContentControl.Loaded"><BeginStoryboard><Storyboard><DoubleAnimation Duration="0:0:0.8"
                                             From="0"
                                             RepeatBehavior="Forever"
                                             Storyboard.TargetName="SpinnerRotate"
                                             Storyboard.TargetProperty="(RotateTransform.Angle)"
                                             To="360" /></Storyboard></BeginStoryboard></EventTrigger></Canvas.Triggers></Canvas></Grid></UserControl>

This is MainWindow.xaml.cs:

 private void Button1_click(object sender, RoutedEventArgs e)
          {

              Thread t = new Thread(new ThreadStart(() => { 
                      Dispatcher.BeginInvoke(new Action(() => { 
                          AnimationView w = new AnimationView();
                          w.Show(); })); })); 
              t.Start();



              foreach (UserControl UC in UserControl)
              {
                  String fileName = UC.Name;

                  String filePath = "D:\ScreenShot";

                   SaveView(view, fileName,  filePath);

              }

        }

public static void SaveView(UserControl view, string fileName,  string destFolder)
        {

                Rect bounds = VisualTreeHelper.GetDescendantBounds(view);

                int width = (int)view.RenderSize.Width;
                int height = (int)view.RenderSize.Height;

                if (width == 0 || height == 0)
                {
                    width = 1920;
                    height = 1080;
                }

                RenderTargetBitmap rtb = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Pbgra32);

                DrawingVisual dv = new DrawingVisual();

                using (DrawingContext ctx = dv.RenderOpen())
                {
                    Size size = new Size(500, 500);
                    if (bounds.Size.IsEmpty == false)
                    {
                        if (bounds.Size.Height > 100)
                        {
                            size = new Size(bounds.Size.Width, bounds.Size.Height - 100);
                        }
                        else
                            size = new Size(bounds.Size.Width, bounds.Size.Height);
                    }

                    VisualBrush vb = new VisualBrush(view);
                    ctx.DrawRectangle(vb, new Pen(Brushes.Blue, 2), new Rect(new Point(0, 100), size));
                    ctx.DrawText(text, new Point(0, 20));
                    ctx.Close();
                }

                //  rtb.Render(view);
                rtb.Render(dv);

                try
                {
                    PngBitmapEncoder jpgEncoder = new PngBitmapEncoder();
                    jpgEncoder.Frames.Add(BitmapFrame.Create(rtb));

                    Byte[] _imageArray;

                    using (MemoryStream outputStream = new MemoryStream())
                    {
                        jpgEncoder.Save(outputStream);
                        _imageArray = outputStream.ToArray();
                    }

                    //Try Find Save Path, if doesn't exists, create it.
                    if (Directory.Exists(destFolder) == false)
                        Directory.CreateDirectory(destFolder);

                    FileStream fileStream = new FileStream(Path.Combine(destFolder, fileName), FileMode.Create, FileAccess.ReadWrite);

                    fileStream.Write(_imageArray, 0, _imageArray.Length);

                    jpgEncoder.Save(fileStream);
                    fileStream.Close();


                }
                catch (Exception e)
                {
                    Log4Net.Instance.Info(System.Reflection.MethodInfo.GetCurrentMethod().ToString());
                    Log4Net.Instance.Info("Exception Generate Screenshot: " + fileName);
                    Log4Net.Instance.Info(e.StackTrace.ToString());
                    Debug.WriteLine(e.ToString());
                }
            }), DispatcherPriority.Loaded);
        }

I hope I can get your help.

Many thanks in advance.


Behaviour for Window.SourceInitialized event

$
0
0

I need to handle Window.SourceInitialized event and for that to do in MVVM pattern I need to write a behaviour for it. When I started writing it, I realized that Window.SourceInitialised is not exposed like Window.LoadedEvent . Please help me in achieving this.

Regards,

Ramakrishna


Ramakrishna


Combobox in datagrid question - displaying a property of the combo in a textbox

$
0
0

I'd like to put a property of a combobox in a textbox on a datagrid.

Combo in a datagrid defined like so:

 

Xaml:

<DataGridTemplateColumn x:Name="cboPartBCPT" Header="CPT Code" Width="100" ><DataGridTemplateColumn.CellTemplate><DataTemplate><TextBlock Text="{Binding CPT}" /></DataTemplate></DataGridTemplateColumn.CellTemplate><DataGridTemplateColumn.CellEditingTemplate ><DataTemplate><ComboBox x:Name="cboPartBCPT"
                                                ItemsSource="{Binding Source = {StaticResource PartB_CPTLookup}}"
                                                SelectedValue="{Binding Path=CPT}"
                                                SelectedValuePath="CPT"
                                                DisplayMemberPath="CPT"
                                                           IsSynchronizedWithCurrentItem="True"></ComboBox></DataTemplate></DataGridTemplateColumn.CellEditingTemplate></DataGridTemplateColumn><DataGridTextColumn x:Name="PartBProcedure" Header="Procedure" Width="200"
                                            Binding="{Binding SelectedItem.ProcedureName, ElementName=cboPartBCPT}" />

PartBProcedure is always blank. What am I doing wrong?


Thanks.

How to get calendar control value in textbox on cahnge of date in date

$
0
0
How to get calendar control value in textbox on cahnge of date in date

WPF:ListView Remove SelectedItem from ImageFileCollectionViewModel

$
0
0

I have a listView which loads images from a directory using the 'ImageViewCollectionModel' along with the 'FileViewModel' .

I have 2 button, one button to 'Delete' the selected image and another button to 'View' the selected image.

When I want to delete, I want to delete from the ListView and also from the directory. Please help me to remove the selected item from the list & also from
the directory. Thank you.

ListView:

<ListView  SelectionMode="Single"  x:Name="ListViewImage" Width="Auto" SelectedItem="{Binding ImageFileName}"
	  ItemsSource="{Binding Path=AllImages}"  Margin="0,20,0,0"
	  VirtualizingStackPanel.IsVirtualizing="True"
	  VirtualizingStackPanel.VirtualizationMode= "Recycling" Height="333" VerticalAlignment="Top"><!--<ListView.ItemContainerStyle><Style TargetType="{x:Type ListViewItem}"><Setter Property="ToolTip" Value="{Binding Path=Thumbnail}" /></Style></ListView.ItemContainerStyle>--><ListView.ItemTemplate><DataTemplate><DataTemplate.Resources><Storyboard x:Key="WaitingTimeline" Timeline.DesiredFrameRate="10"><DoubleAnimationUsingKeyFrames BeginTime="00:00:00" RepeatBehavior="Forever" 
					Storyboard.TargetName="WaitingImage" 
					Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0]
											   .(RotateTransform.Angle)"><SplineDoubleKeyFrame KeyTime="00:00:00" Value="-15"/><SplineDoubleKeyFrame KeyTime="00:00:03" Value="15"/></DoubleAnimationUsingKeyFrames></Storyboard></DataTemplate.Resources><StackPanel Orientation="Horizontal" Height="100"><Border BorderBrush="GhostWhite" BorderThickness="2" ><Image x:Name="ThumbnailImage" Margin="2" Visibility="Collapsed" Height="150" Width="150" Source="{Binding Path=Thumbnail}" ></Image></Border><Image x:Name="WaitingImage" Visibility="Visible" Height="20" Width="20" Source="./Hourglass.png"><Image.RenderTransform><TransformGroup><RotateTransform Angle="0" CenterX="10" CenterY="10"/></TransformGroup></Image.RenderTransform></Image><TextBlock Margin="10,40,0,0" FontStyle="Italic" FontWeight="SemiBold" Foreground="#1432AA" Text="{Binding Path=ShortName}" /></StackPanel><DataTemplate.Triggers><DataTrigger Binding="{Binding Path=IsLoaded}" Value="True"><Setter Property="Visibility" TargetName="ThumbnailImage" Value="Visible"/><Setter Property="Visibility" TargetName="WaitingImage" Value="Collapsed"/></DataTrigger><DataTrigger Binding="{Binding Path=IsLoaded}" Value="False"><Setter Property="Visibility" TargetName="WaitingImage" Value="Visible"/><Setter Property="Visibility" TargetName="ThumbnailImage" Value="Collapsed"/><DataTrigger.EnterActions><BeginStoryboard x:Name="WaitingTimeline_BeginStoryboard" Storyboard="{StaticResource WaitingTimeline}"/></DataTrigger.EnterActions><DataTrigger.ExitActions><StopStoryboard BeginStoryboardName="WaitingTimeline_BeginStoryboard"/></DataTrigger.ExitActions></DataTrigger></DataTemplate.Triggers></DataTemplate></ListView.ItemTemplate></ListView><Button Content="Edit" HorizontalAlignment="Left" Margin="73,380,0,0" VerticalAlignment="Top" Height="150" Width="150" Name="Edit_Photo" Click="Edit_Photo_Click"/><Button Content="Delete" HorizontalAlignment="Left" Margin="475,380,0,0" VerticalAlignment="Top" Height="150" Width="150" Name="Delte_Photo" Click="Delte_Photo_Click"/><Label Name="lImageName"  Margin="228,448,234,82" HorizontalContentAlignment="Center" Foreground="ForestGreen" FontWeight="Bold" Content="{Binding SelectedItem.ShortName, ElementName=ListViewImage}" >


C# Code:

 public ImggLList()
        {
            InitializeComponent();
            ListViewImage.Items.Clear();
            DataContextChanged += OnDataContextChanged;
            string destination_dir = System.IO.Directory.GetCurrentDirectory() + @"./4x6";
            ImageFileCollectionViewModel ImagesViewModel = new ImageFileCollectionViewModel();
            ImageFileControler.CompleteViewList(ImagesViewModel, destination_dir);
            ListViewImage.DataContext = ImagesViewModel;
        }

        private ImageFileCollectionViewModel _currentDataContext = null;
        private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if (_currentDataContext == DataContext) return;

            if (_currentDataContext != null)
                _currentDataContext.SelectedImageFileViewModels = null;

            _currentDataContext = DataContext as ImageFileCollectionViewModel;
            if (_currentDataContext != null)
                _currentDataContext.SelectedImageFileViewModels = ListViewImage.SelectedItems;
            
        }

       
        public string getImageName { get; set; }
        private void Edit_Photo_Click(object sender, RoutedEventArgs e)
        {
             //getImageName = lImageName.Content.ToString();
            var openImageEditingWindow = new PhotoView(this);
            openImageEditingWindow.ShowDialog();
        }

        private List<ImageFileViewModel> copyOfSelection;
        private ImageFileCollectionViewModel imageFileCollection;
        private void Delte_Photo_Click(object sender, RoutedEventArgs e)
        {
             copyOfSelection = imageFileCollection.SelectedImageFileViewModels.Cast<ImageFileViewModel>().ToList();

            foreach (ImageFileViewModel ifvm in copyOfSelection)
            {
                copyOfSelection.Remove(ifvm);
            }
        }
}

ImageFileCollectionViewModel.cs

using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using ImagePrintUtility.Model;

namespace ImagePrintUtility.ViewModel
{
    public class ImageFileCollectionViewModel: INotifyPropertyChanged
    {
        private ObservableCollection<ImageFileViewModel> _allImages;
        private int dataItemsCount;
        public ObservableCollection<ImageFileViewModel> AllImages
        {
            get { return _allImages; }
        }

        public int DataItemsCount
        {
            get
            {
                return dataItemsCount;
            }
            private set
            {
                dataItemsCount = value;
                OnPropertyChanged("DataItemsCount");
            }
        }

        public ImageFileCollectionViewModel()
        {
            this._allImages = new ObservableCollection<ImageFileViewModel>();
            this.DataItemsCount = 0;
        }

        public void AddNewPhotoItem(IImageFile imageFile)
        {
            ImageFileViewModel newImageFileViewModel = new ImageFileViewModel(imageFile);
            this._allImages.Add(newImageFileViewModel);
            this.DataItemsCount++;
        }
        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        private IList _selectedImageFileViewModels;
        public IList SelectedImageFileViewModels
        {
            get { return _selectedImageFileViewModels; }
            set
            {
                if (_selectedImageFileViewModels != value)
                {
                    _selectedImageFileViewModels = value;
                    OnPropertyChanged("SelectedImageFileViewModels");
                }
            }
        }

}

FileViewModel.cs

using System.ComponentModel;
using System.IO;
using ImagePrintUtility.Model;

namespace ImagePrintUtility.ViewModel
{
    public class FileViewModel: INotifyPropertyChanged
    {
        protected IImageFile _imageFile;


        public string ShortName
        {
            get { return Path.GetFileName(_imageFile.FileName); }
        }
        

        public string FileName
        {
            get { return _imageFile.FileName; }
        }

        public FileViewModel(IImageFile imageFile)
        {
            this._imageFile = imageFile;
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

    }

    
}

the necessary WPF .dll files

$
0
0

Hi all,

There are four .dll files necessary to compile any WPF application:

1. PresentationCore.dll

2. PresentationFrameword.dll

3. WindowsBase.dll

4. System.Xaml.dll

They are located in:

c:\Program Files\Reference Assemblies\Microsoft\Framework\.NetFramework\V4.0

- Why aren't those files included by default, such as WinForms .dlls?

- How do you know, at runtime, the location of those files?

Thank you

Handle Manipulation Events for Controls in a ScrollViewer

$
0
0

Hi Guys

I have the following part in the XAML. The WrapPanel holds images during runtime which should be draggable over the surrounding Grid: 

<controls:TwoFingerScrollViewer x:Name="ScollPane" PanningMode="VerticalOnly" VerticalScrollBarVisibility="Hidden"><WrapPanel x:Name="SmallImagePreviewPanel"></WrapPanel></controls:TwoFingerScrollViewer>
The 'TwoFingerScrollViewer' just overrides the OnManipulationDelta of the ScrollViewer where it checks whether there are more than one touch-device scrolling or not. When there is just one touch-device the event is not handled. 

To handle all the ManipulationEvents for the controls within the ScrollViewer I used the addHandler method which works more or less with the normal ScrollViewer. Anyway somehow the ManipulationCompletedEvent is never fired when using only one touch-device (with the TwoFingerScrollViewer). 

Is there a dependency between the ManipulationDelta and ManipulationCompleted events (so that it wouldn't be possible to not handle the ManipulationDelta when using just one touch-device). Or what am I missing? 

Thanks for your help! 


 

How to override MaxLength Property for WPF TextBox control

$
0
0

For my WPF apps I have created a couple custom controls based on a TextBox. These include NumericTextBox, WatermarkTextBox, and ReturnTextBox.

Numeric and Watermark inherit from ReturnTextBox, which inherits from TextBox.

When I go to use any of my custom textboxes they work great. The one problem seems to be NumericTextBox and the MaxLength property. The property is now ignored and does not work. There is no code in any of my custom controls overriding or messing with the MaxLength property.

When I use MaxLength on my ReturnTextBox, it works just as you would expect:

<ui:ReturnTextBox MaxLength="35" Width="500" Background="LightYellow"

Text="{Binding BrRptCorpName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged,

ValidatesOnDataErrors=True}" TabIndex="2" />

However when I use the property on my NumericTextBox it is ignored and does not work:

<ui:NumericTextBox MaxLength="9" Background="LightYellow" Text="{Binding BrRptAmt,

Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" TabIndex="1" />

Can anyone help me figure out why MaxLength stops working? Is it because NumericTextBox does not directly inherit from TextBox? Should I be overriding MaxLength property in ReturnTextBox so it can be used by Numeric?

Thank you for your help!


Resize controls in a list to fill the available space WPF

$
0
0

I'm trying to find a way to display a horizontal List of items in WPF, the trick is that the Window which contains the List will be displayed on various screen sizes and all the items in the list need to be resized to fill the available space without any use of scroll bars.

I've found that a ViewBox control can be used to achieve the desired affect, but the ViewBox works only if I set<RowDefinition Height="300"/>.This approach doesn't work because if you have a certain number of items in the List they start becomingcut off.

If I remove <RowDefinition Height="300"/> then the first item in the list fills the screen and the rest arecut off

Any suggestions on how I can make all the items in the list resize to fill the available space no matter what the screen resolution is?

XAML:

<Window x:Class="ViewBoxExample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" WindowState="Maximized"><ItemsControl ItemsSource="{Binding Path=Employees}"><ItemsControl.ItemTemplate><DataTemplate><Grid><Grid.ColumnDefinitions><ColumnDefinition Width="3*" /><ColumnDefinition Width="3*" /><ColumnDefinition Width="3*" /></Grid.ColumnDefinitions><Grid.RowDefinitions><RowDefinition Height="300"/></Grid.RowDefinitions><Viewbox Grid.Row="0" Grid.Column="0"><TextBlock Text="{Binding Path=Name}" /></Viewbox><Viewbox Grid.Row="0" Grid.Column="1"><TextBlock Text="{Binding Path=Surname}" /></Viewbox><Viewbox Grid.Row="0" Grid.Column="2"><TextBlock Text="{Binding Path=Age}" /></Viewbox></Grid></DataTemplate></ItemsControl.ItemTemplate></ItemsControl></Window>

C#: 

using System.Collections.Generic;
using System.Windows;

namespace ViewBoxExample
{
    public partial class MainWindow : Window
    {
        public List<Employee> _employees = new List<Employee>();
        public List<Employee> Employees 
        {
            get { return _employees; }
            set { _employees = value; }
        }

        public MainWindow()
        {
            InitializeComponent();

            Employees = new List<Employee>()
            {
                new Employee{ Name="Name1",Surname="Surname1",Age=20},
                new Employee{ Name="Name2",Surname="Surname2",Age=30},
                new Employee{ Name="Name3",Surname="Surname3",Age=40},
                new Employee{ Name="Name4",Surname="Surname4",Age=50},
                new Employee{ Name="Name5",Surname="Surname5",Age=60},
            };
            this.DataContext = this;
        }
    }

    public class Employee
    {
        public string Name { get; set; }
        public string Surname { get; set; }
        public int Age { get; set; }
    }
}

 

Possible bug in System.Windows.Controls.Primitives.MultiSelector class

$
0
0

With reference to this issue at CodePlex - https://wpfextendeddatagrid.codeplex.com/workitem/1065

I am reasonably certain there is a bug that prevents items that have value equality - as expressed through an override of "Equals" - but not reference equality - from being removed from the SelectedItems property even if IList.RemoveAt is called with the proper item index.

  1. To recreate this, go to the above link and download both attachments.
  2. Download the source code for the project reference above (Extended Data Grid).
  3. Replace "DataGrid.cs" in the Extended Data Grid project with the "DataGrid.cs" file in DataGrid.zip that is attached to the issue.
  4. Build the Extended Data Grid Project.
  5. Use the resulting ExtendedGrid.dll to build the project that is attached to the issue as a demonstration.
  6. Use the exe from the issue demo project as the debug executable for the Extended Data Grid project and Run.
  7. Press Load Test Data
  8. control-click two different items in the list that have the same text in the File Name column
  9. Set a breakpoint in the Extended Data Grid function "DataGrid.MakeFullRowSelection" at the point where EndUpdateSelectedItems is called.
  10. Now control-click the second selected item and note that even though that item should be removed from the SelectedItems collection, it is not.
As long as "Equals" returns nonequivalence for items in the SelectedItems collection, the item is removed, however, if the items are referentially different and .Equals returns equivalence, the deselected item is not properly removed.

Server Object Error

$
0
0

While I am running my website[which is written using Asp] in my server I am getting this Error. But the same project runs well in another server. Could anyone please help me to resolve this error?

Microsoft OLE DB Provider for ODBC Drivers error '800401f3'

[Microsoft][ODBC SQL Server Driver][SQL Server]Changed database context to 'ISTap'.

folder/subfolder/sample.asp, line 18

How to handle MouseUp event on a ContextMenu

$
0
0

Hey there,

I have an Image that represents a button, and I created a ContextMenu to drop down when image is clicked. I have also added some StackPanels to the ContextMenu and I added Image and Textblock to each Stackpanel so they pretend as menu items.

Look at my work: 

So, the problem is that I need to get click from the menu item, not just from Stackpanel, because Stackpanel is smaller than the width of menu item.

Here's my XAML:

<Image x:Name="Sucelje_Slika_Datoteka" MouseUp="DatotekaMeni_Klik" ContextMenuService.IsEnabled="False" HorizontalAlignment="Left" Height="29" VerticalAlignment="Top" Width="76"><Image.ContextMenu><ContextMenu> <StackPanel Orientation="Horizontal" Width="240"><Image Source="Resources/NoviDokumentIkona.png" Width="30" Height="30"/><TextBlock Text="Novi dokument..." Margin="10,0,0,0" FontFamily="Titillium" FontSize="16" VerticalAlignment="Center"/></StackPanel><StackPanel Orientation="Horizontal"><Image Source="Resources/OtvoriDokumentIkona.png" Width="30" Height="30"/><TextBlock Text="Otvori dokument..." Margin="10,0,0,0" FontFamily="Titillium" FontSize="16" VerticalAlignment="Center"/></StackPanel>

</Image>

Please help!


Knowledge: C, C++, C#, Java, Pawn


Binding Command to Button within DataTemplate

$
0
0

Hi,

I am using WPF Toolkit in my project. And I have DataGrid in my XAML.
Now I have added one button in one column using DataTemplate.

I have binded DataView to this Grid. But the only problem am facing is am not able to bind Command to the Button within datatemplate.

I have written following XAML to bind command to this button

<Button Content="..." Command = "{Binding Path=ShowDealListCommand}"/>

 

But when I clicked this button it's not calling target method I have written in this command.

I am able to bind content property to this button so this means that there is no issues of setting datacontext. As I have already set DataContext for this XAML in Codebehind.

 

Pls help me !!

 

Thanks ! :)

 

WPF Canvas - can a line be one pixel long?

$
0
0

Hi, I'm writing some rendering code and am using Line objects on a Canvas.

The Lines are quite simple:

                Line line = new Line();
                line.Stroke = System.Windows.Media.Brushes.Black;
                line.StrokeThickness = 1;
                line.X1 = ???;
                line.Y1 = ???;
                line.X2 = ???;
                line.Y2 = ???;

Now, if the line length is > 1 the line renders fine. ie, X1 = 10, X2 = 10, Y2 = 20

However, if all coordinates are the same, to X1 = Y1 = X2 = Y2 = 10, no line is rendered.

The behaviour I would *like* is one pixel is drawn.

Is there anyway to force this please?

Thanks,

T

Question about sorting Detail table

$
0
0

Someone posted almost the exact same question here.  I attempted to use that answer in my situation but am not sure how to form the syntax.  I'm using WPF and EF.

I, too, have a master/detail situation that uses a combo box that fills a datagrid.  The combo is sorted by patient name.  I'd like the grid to sort by appointment date.

The EF wizard created the following code (I added the sort description).

        Dim TblPatientDemographicViewSource As System.Windows.Data.CollectionViewSource =
            CType(Me.FindResource("TblPatientDemographicViewSource"), System.Windows.Data.CollectionViewSource)

        'sort view by patient name.  
        TblPatientDemographicViewSource.SortDescriptions.Add(New SortDescription("PatientName", ListSortDirection.Ascending))

        'Load data by setting the CollectionViewSource.Source property:
        'TblPatientDemographicViewSource.Source = [generic data source]
        _context.tblPatientDemographics.Load()
        TblPatientDemographicViewSource.Source = _context.tblPatientDemographics.Local

The suggested answer (converted to vb.net from c#):

        DirectCast(TblDentistAppointmentsDataGrid.Items, ItemCollection).SortDescriptions.Add(New System.ComponentModel.SortDescription("DentistAppointmentDate", System.ComponentModel.ListSortDirection.Ascending))

I'm not sure where to place this suggested code in my code block.  More importantly, I'm not sure the syntax is correct.  Looking at the xaml, I noticed the resource name:

<DataGrid x:Name="TblDentistAppointmentsDataGrid" AutoGenerateColumns="False" EnableRowVirtualization="True" 
                  ItemsSource="{Binding Source={StaticResource TblPatientDemographictblDentistAppointmentsViewSource}}" 
I thought maybe that resource is what I should apply the sort description to but that is not an option when forming the syntax. 

Thanks.



How to make multicolor in a single cell of DataGrid based on condition

$
0
0
Hello,
 
I need to make a multicolor in a single cell based on cell value in WPF datagrid.
 
For example:
I have a column which header is "InitialNames" and another column with a header "Available"
 
Let's say that it contains for example the following:
InitialNames
ABC/BD
BVF/GFD/YA
BD
 
Avaiable
0/1
0/0/0
1
 
It is all the time the substring.count for both columns in one row are the same.
 
What I need is that to substring the cell "available" based on "/" and if the value is 1 then the color of the same index in InitialNames column will be red.
 
I know how to do it in code using TextBlock.Inlines but I don't know how to replace the result in the datagrid cell "InitialNames" with the new inlines colored string.

Change the following event from user control to viewModel

$
0
0
Hi 

I need to move this event from the user control to the viewModel,I have read the following link 
but not sure that I got it since command are true or false,my question is assume that I have the following event 
how should I change it to the viewModel.? 


Please assist ,Im really stuck !!!!
 

http://blog.magnusmontin.net/2013/06/30/handling-events-in-an-mvvm-wpf-application/




        private void DropText_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            var textBox = (TextBox) sender;
            if (textBox == null) return;
            textBox.Focus();
            var dataObject = new DataObject((textBox).Text);
            dataObject.SetData(DragSource, sender);
            DragDrop.DoDragDrop(textBox, dataObject, DragDropEffects.Copy | DragDropEffects.Move);
        }



<TextBox x:Name="Job"  
        			AcceptsReturn="True"
        			AllowDrop="True" 
        			PreviewMouseDown="DropText_PreviewMouseDown"
        			SelectionChanged="listbox_SelectionChanged"
        			HorizontalAlignment="Left" 





    internal class RelayCommand : ICommand
    {
        readonly Action _execute;
        readonly Func<bool> _canExecute;

        public RelayCommand(Action execute)
            : this(execute, null)
        {
        }

        public RelayCommand(Action execute, Func<bool> canExecute)
        {
            if (execute == null)
                throw new ArgumentNullException("execute");
            _execute = execute;
            _canExecute = canExecute;
        }

        public bool CanExecute(object parameter)
        {
            return _canExecute == null ? true : _canExecute();
        }

        public event EventHandler CanExecuteChanged
        {
            add
            {
                if (_canExecute != null)
                    CommandManager.RequerySuggested += value;
            }
            remove
            {
                if (_canExecute != null)
                    CommandManager.RequerySuggested -= value;
            }
        }

        public void Execute(object parameter)
        {
            _execute();
        }

        public event EventHandler CanExecuteChange;
        public void RaiseCanExecuteChange()
            {
            if (CanExecuteChange != null)
                CanExecuteChange(this, new EventArgs());
            }


How to clear a WriteableBitmap?

$
0
0

Hello all. Is there a fast way to clear (zero-out) the pixels in a WriteableBitmap...something like WriteableBitmap.Clear()? I don't see anything in the docs. Currently I'm copying in a large array of zeros to do this and it seems a little clunky. Thanks in advance.

L

Reg saving rotated image from image control in WPF

$
0
0

Hello,

I have rotated image by some angle by applying transform to image control as shown below.

RotateTransform rt = newRotateTransform(angleNew); image1.RenderTransform = rt;

image1 is image control.

How can I save this rotated image? Tried below code, but, it is saving original image without rotation.

var encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create((BitmapSource)image1.source));
using (FileStream stream = new FileStream("D:\\TestImage.png", FileMode.Create))
      encoder.Save(stream);

             


Harish

How to display text in an Arc

$
0
0

Dear all,

I am the following visual

Based on that visual as you can see I need to display text information inside an arc which contains a Texbloc.
At a predefine time the green arc should animate from 0 to Text length.
Then after 10s delay, the green arc animate back to 0 and a new text is set for the text box and the sequence restart.

Any idea how can I do this knowing that I do not know in advance the text lenth

thanks for help

regards

Viewing all 18858 articles
Browse latest View live


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