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

Text Search and extraction from pdf files.

$
0
0

I want to extract the searched text from a pdf doc and display it. I am using this code but not getting the result not even the searched text while debugging. Can anyone help with the correct code or logic. Thanks!

 

<Grid>

       <Grid.RowDefinitions>

           <RowDefinition />

           <RowDefinition Height="Auto" />

       </Grid.RowDefinitions>

       <TextBox x:Name="textBox" HorizontalAlignment="Left" Height="23" TextWrapping="Wrap" VerticalAlignment="Top" Width="230" TextChanged="textBox_TextChanged" Margin="20,20,0,0"/>

       <Button x:Name="button" Content="Search" HorizontalAlignment="Left" Margin="285,20,0,0" VerticalAlignment="Top" Width="75" Click="button_Click"/>

       <Grid Margin="10,60,10.4,9.8">

           <ItemsControl Name="pdftext">

               <ItemsControl.ItemTemplate>

                   <DataTemplate>

                       <Grid Margin="0,0,0,5">

                           <Grid.ColumnDefinitions>

                               <ColumnDefinition Width="*" />

                                <ColumnDefinition Width="100" />

                           </Grid.ColumnDefinitions>

                           <TextBlock Text="{Binding Title}" />

                           <ProgressBar Grid.Column="1" Minimum="0" Maximum="100" Value="{Binding Completion}"                             />

                       </Grid>

                   </DataTemplate>

               </ItemsControl.ItemTemplate>

           </ItemsControl>

       </Grid>

Cs page:

privatevoid button_Click(object sender, RoutedEventArgs e)

        {

           string filename = System.AppDomain.CurrentDomain.BaseDirectory;

            filename =@"D:\Tourists.pdf";

           if (File.Exists(filename))

            {

               try

                {

                   StringBuilder text =newStringBuilder();

                   PdfReader pdfReader =newPdfReader(filename);

                   for (int page = 1; page <= pdfReader.NumberOfPages; page++)

                    {

                       ITextExtractionStrategy strategy =newSimpleTextExtractionStrategy();

                       string currentText =PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy);

                        text.Append(System.Environment.NewLine);

                        text.Append("\n Page Number:"+ page);

                        text.Append(System.Environment.NewLine);

                        currentText =Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default,Encoding.UTF8,Encoding.Default.GetBytes(currentText)));

                        text.Append(currentText);

                        pdfReader.Close();

                    }

                    pdftext.DataContext += text.ToString();

                }

                catch (Exception ex)

                {

                   MessageBox.Show("Error: "+ ex.Message, "Error");

                }

            }

          }


Control Template Menu Item

$
0
0

Hi,

I am having an issue with the MenuItem Control Template. I have made a copy of the Control Template and put it into my MenuItem Style but I can't seem to make it work.

Here is the XAML for the Style:

<!--Menu Style--><Style x:Key="AppMenu" TargetType="{x:Type Menu}"><Setter Property="Foreground" Value="{StaticResource S2ENGINEHD.LightText}"/><Setter Property="FontFamily" Value="Segeo UI Light"/><Setter Property="Background" Value="Transparent"/><Setter Property="BorderThickness" Value="0"/></Style><!--Menu Item Style--><Style x:Key="AppMenuItem" TargetType="{x:Type MenuItem}"><Setter Property="Foreground" Value="{StaticResource S2ENGINEHD.LightText}"/><Setter Property="FontFamily" Value="Segeo UI Light"/><Setter Property="Background" Value="{StaticResource S2ENGINEHD.MediumBackground}"/><Setter Property="BorderThickness" Value="0"/><!--Menu Item Control Template--><Setter Property="Template"><Setter.Value><ControlTemplate x:Name="MenuItemControlTemplate" TargetType="{x:Type MenuItem}"><Border x:Name="templateRoot"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}"
                            Background="{TemplateBinding Background}"
                            SnapsToDevicePixels="True"><!--Item Holder--><Grid VerticalAlignment="Center"><Grid.ColumnDefinitions><ColumnDefinition Width="Auto"/><ColumnDefinition Width="Auto"/></Grid.ColumnDefinitions><!--Icon Menu Item Content Placement--><ContentPresenter x:Name="Icon"
                                              Content="{TemplateBinding Icon}"
                                              ContentSource="Icon" HorizontalAlignment="Center"
                                              Height="16" Margin="3"
                                              SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
                                              VerticalAlignment="Center" Width="16"/><!--Line Separator--><Path x:Name="GlyphPanel"
                                  Data="F1M10,1.2L4.7,9.1 4.5,9.1 0,5.2 1.3,3.5 4.3,6.1 8.3,0 10,1.2z"
                                  Fill="{TemplateBinding Foreground}"
                                  FlowDirection="LeftToRight"
                                  Margin="3"
                                  Visibility="Collapsed"
                                  VerticalAlignment="Center"/><!--Menu Item Content Placement--><ContentPresenter ContentTemplate="{TemplateBinding HeaderTemplate}"
                                              Content="{TemplateBinding Header}"
                                              Grid.Column="1"
                                              ContentStringFormat="{TemplateBinding HeaderStringFormat}"
                                              ContentSource="Header" Margin="{TemplateBinding Padding}"
                                              RecognizesAccessKey="True"
                                              SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/><Popup x:Name="PART_Popup"
                                   AllowsTransparency="True"
                                   Focusable="False"
                                   IsOpen="{Binding IsSubmenuOpen, RelativeSource={RelativeSource TemplatedParent}}"
                                   PopupAnimation="{DynamicResource {x:Static SystemParameters.MenuPopupAnimationKey}}"
                                   Placement="Bottom"><!--Sub Menu--><Border x:Name="SubMenuBorder"
                                        BorderBrush="#FF646464"
                                        BorderThickness="0"
                                        Background="#FF646464"
                                        Padding="2"><ScrollViewer x:Name="SubMenuScrollViewer"
                                                  Style="{DynamicResource {ComponentResourceKey ResourceId=MenuScrollViewer, TypeInTargetAssembly={x:Type FrameworkElement}}}"><Grid RenderOptions.ClearTypeHint="Enabled"><Canvas HorizontalAlignment="Left" Height="0" VerticalAlignment="Top" Width="0"><Rectangle x:Name="OpaqueRect" Fill="{Binding Background, ElementName=SubMenuBorder}" Height="{Binding ActualHeight, ElementName=SubMenuBorder}" Width="{Binding ActualWidth, ElementName=SubMenuBorder}"/></Canvas><Rectangle Fill="#FFD7D7D7" HorizontalAlignment="Left" Margin="29,2,0,2" Width="1"/><ItemsPresenter x:Name="ItemsPresenter"
                                                            KeyboardNavigation.DirectionalNavigation="Cycle"
                                                            Grid.IsSharedSizeScope="True"
                                                            SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
                                                            KeyboardNavigation.TabNavigation="Cycle"/></Grid></ScrollViewer></Border></Popup></Grid></Border><ControlTemplate.Triggers><Trigger Property="IsSuspendingPopupAnimation" Value="True"><Setter Property="PopupAnimation" TargetName="PART_Popup" Value="None"/></Trigger><Trigger Property="Icon" Value="{x:Null}"><Setter Property="Visibility" TargetName="Icon" Value="Collapsed"/></Trigger><Trigger Property="IsChecked" Value="True"><Setter Property="Visibility" TargetName="GlyphPanel" Value="Visible"/><Setter Property="Visibility" TargetName="Icon" Value="Collapsed"/></Trigger><Trigger Property="IsHighlighted" Value="True"><Setter Property="Background" TargetName="templateRoot" Value="#FF646464"/><Setter Property="BorderBrush" TargetName="templateRoot" Value="#FF646464"/></Trigger><Trigger Property="IsEnabled" Value="False"><Setter Property="TextElement.Foreground" TargetName="templateRoot" Value="#FF646464"/><Setter Property="Fill" TargetName="GlyphPanel" Value="#FF646464"/></Trigger><Trigger Property="IsMouseOver" Value="True"><Setter Property="Background" TargetName="templateRoot" Value="#FF646464"/></Trigger><Trigger Property="CanContentScroll" SourceName="SubMenuScrollViewer" Value="False"><Setter Property="Canvas.Top" TargetName="OpaqueRect" Value="{Binding VerticalOffset, ElementName=SubMenuScrollViewer}"/><Setter Property="Canvas.Left" TargetName="OpaqueRect" Value="{Binding HorizontalOffset, ElementName=SubMenuScrollViewer}"/></Trigger></ControlTemplate.Triggers></ControlTemplate></Setter.Value></Setter></Style>

I'm not to sure where I am going wrong, I haven't made any changes to the template copy apart from putting it into my Resource Dictionary.

Windows 10 Build 1607 (Anniversary) broke printing WPF FixedDocument?

$
0
0

I have an application that can't print on Windows 10 Anniversary edition under certain conditions. Before the Anniversary update, it printed under all known conditions and older Windows versions (7,8,10). There is no problem printing to PDF/XPS. Other applications can print normally.

The code is roughly like:

var printDialog = new PrintDialog {UserPageRangeEnabled = false}; ... printDialog.ShowDialog(); var fixedDocument = new FixedDocument(); var txtBlock = new TextBlock {Text = $"{contentTextBox.Text}"};
//contentTextBox.Text empty or spaces only, does not print
//txtBlock.Foreground = new SolidColorBrush(Color.FromArgb(0,0,0,0)); //does not print
//txtBlock.Foreground = new SolidColorBrush(Color.FromArgb(10,0,0,0)); //prints
FixedPage.SetLeft(txtBlock, 0); FixedPage.SetTop(txtBlock, 0); var image = new Image { ... }; FixedPage.SetLeft(image, 0); FixedPage.SetTop(image, 0); var fixedPage = new FixedPage { ... }; fixedPage.Children.Add(image); fixedPage.Children.Add(txtBlock); fixedPage.Measure(sz); fixedPage.Arrange(new Rect(new Point(), sz)); fixedPage.UpdateLayout(); var pageContent = new PageContent(); ((IAddChild)pageContent).AddChild(fixedPage); fixedDocument.Pages.Add(pageContent); printDialog.PrintDocument(fixedDocument.DocumentPaginator, $"WpfTestDocument {DateTime.Now:hh:mm:ss}");

If contentTextBox.Text is empty, print does not happen. If ForegroundColor is transparent, print does not happen. "Print does not happen": I see the print job spooled up in Windows' print queue and quickly disappear. In EventViewer (Microsoft-Windows-PrintService/Operational) I see the print job spooled, and promptly deleted.

My test application is here (for VS 2015): https://1drv.ms/u/s!AmCoZxIrIzCrgmte4iwkpxOf7STO 






WPF Dead or Not?

$
0
0

We've seen all the postings about WPF being Dead.  We heard from MSFT it was not, and they were starting to work on it again.  It's now about two years later and we see next to nothing regarding progress in WPF.   WPF was cutting edge technology and MVVM was "borrowed" by Angular to do client side binding very similar to what we already did with MVVM.  C'mon MSFT "Get Going"...  You're inaction is speaking loudly to us WPF adopters.

Should MSFT open source WPF being that they are unwilling to move it forward? 

Or should MSFT put a real plan together and let us know what's going on.  

Or is MSFT saying to us Typescript is the future and everything should be hosted in a browser which they don't have for WPF (without airspace issues).  

Here's a suggestion for MSFT, give us real browser so that we want and choose to embed your browser rather than CEF (Chrome Embedded Framework).  

Mouse Events in WPF

$
0
0

Hi

I have a custom UserControl containing a few items. I want to be able to trigger mouse events on the button control. I am aware of the bubbling/tunnelling event structures but am hardly expert. I have found several promising answers to this question but my events still do not fire. The UserControl events Tile_PreviewMouseMove and TileClick work fine. But even when I remove these two events the Button events still do not fire. Here is the XAML:

<UserControl
    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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    x:Class="Tile"
    x:Name="UserControl"
    d:DesignWidth="640" d:DesignHeight="480" Width="110" Height="100" Opacity="1" MouseUp="TileClick" PreviewMouseMove="Tile_PreviewMouseMove" ><UserControl.Resources><Storyboard x:Key="OnMouseEnter1"><DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="TileSurfaceRct"
                                           Storyboard.TargetProperty="(UIElement.Opacity)"><SplineDoubleKeyFrame KeyTime="00:00:00" Value="0" /><SplineDoubleKeyFrame KeyTime="00:00:00.3000000" Value="0.14" /></DoubleAnimationUsingKeyFrames></Storyboard><Storyboard x:Key="OnMouseLeave1"><DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="TileSurfaceRct"
                                           Storyboard.TargetProperty="(UIElement.Opacity)"><SplineDoubleKeyFrame KeyTime="00:00:00" Value="0.14" /><SplineDoubleKeyFrame KeyTime="00:00:00.3000000" Value="0" /></DoubleAnimationUsingKeyFrames></Storyboard></UserControl.Resources><UserControl.Triggers><EventTrigger RoutedEvent="Mouse.MouseEnter"><BeginStoryboard Storyboard="{StaticResource OnMouseEnter1}" /></EventTrigger><EventTrigger RoutedEvent="Mouse.MouseLeave"><BeginStoryboard Storyboard="{StaticResource OnMouseLeave1}" x:Name="OnMouseLeave1_BeginStoryboard" /></EventTrigger></UserControl.Triggers><Grid x:Name="LayoutRoot" Cursor="Hand" Background="Transparent" ><Rectangle StrokeThickness="0" x:Name="TileBgrndRct" Fill="White" /><TextBlock Margin="2,2,20,34" x:Name="TileTxtBlck" FontSize="12" Foreground="#FFFFFFFF" Text="Tile "
                   TextWrapping="Wrap" /><Image HorizontalAlignment="Left" Margin="2,0,0,2" x:Name="TileIcon" VerticalAlignment="Bottom" Width="40"
               Height="40" Stretch="Uniform"  /><Button HorizontalAlignment="Right" Margin="0,0,2,2" x:Name="InfoButton" VerticalAlignment="Bottom" Width="40"
               Height="40"  Cursor="Help" PreviewMouseUp="InfoButtonClick" MouseUp  = "InfoButtonClick"   PreviewMouseMove="InfoButtonMouseMove"/><Rectangle x:Name="TileSurfaceRct" Fill="#FF000000" Opacity="0" Stroke="#FFFBFBFB" /><Border x:Name="TileBorder" BorderBrush="White" BorderThickness="2" HorizontalAlignment="Left" Height="100" VerticalAlignment="Top" Width="110" /><Rectangle StrokeThickness="0" RenderOptions.EdgeMode="Aliased" x:Name="DogearRct" Fill="#1F1D35"  HorizontalAlignment="Right" Height="20" VerticalAlignment="Top" Width="20" /><Polygon x:Name="DogearTri" Points="92,2 92,18, 108,18" Stroke="White" Fill="White"  /></Grid></UserControl>

Thanks for your help.

Ozs


System.Windows.Clipboard.GetDataObject throws OutOfMemoryException

$
0
0

I have a very strange problem in my WPF application(s), see the call stack below:

Stacktrace:
   bei System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
   bei System.Windows.Clipboard.GetDataObjectInternal()
   bei System.Windows.Documents.TextEditorCopyPaste.OnQueryStatusPaste(Object target, CanExecuteRoutedEventArgs args)
   bei System.Windows.Input.CommandBinding.OnCanExecute(Object sender, CanExecuteRoutedEventArgs e)
   bei System.Windows.Input.CommandManager.FindCommandBinding(Object sender, RoutedEventArgs e, ICommand command, Boolean execute)

The exception thrown is System.OutOfMemoryException. Using MS referencesource site, the HRESULT is a result of an OleGetClipboard call. Why would this method run out of memory, it's just getting an interface to the clipboard. It's not documented either and I did not find any such case using Bing or Google. I cannot reproduce the problem on my machine, I tried allocating big strings and setting them into clipboard, but when it happens on client's machines, it is enough to select a short text and copy it in the clipboard outside the application and the problem is gone. It's probably something in our code, but I checked all occurrences of clipboard manipulation and they all look okay. No threads involved, etc. Does anybody have an idea what this can be or what should I look into? Thanks.

ETA: If it helps, I have this information about OS on 2 machines where it happened (taken from environment variables). They are both the same, significant, perhaps?

OSVersion='Microsoft Windows NT 6.2.9200.0', Is64BitOperatingSystem='True'

How to programmatically expand a tree view control?

$
0
0

I want to programmatically expand all the nodes on a tree view control.  You would think this would be easy especially since the tree view item has an IsExpanded property: 

    TreeViewItem item = (TreeViewItem)treeView.ItemContainerGenerator.ContainerFromItem(o);

    item.IsExpanded = true;

 
But I am getting a NullReferenceException when looping through the tree view items.  I think that the problem is being caused by tree view virtualization.  But I tried turning it off and it doesn't seem to make a difference:

<TreeView Height="200" HorizontalAlignment="Left" Margin="71,34,0,0" Name="treeView1" VerticalAlignment="Top" Width="120"

     VirtualizingStackPanel.IsVirtualizing="False"/>

                 
Anyway, I created a simple sample app which demonstrates the problem.                   

<Window x:Class="WpfApplication13.MainWindow"

  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

  Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded"><Grid><TreeView Height="200" HorizontalAlignment="Left" Margin="71,34,0,0" Name="treeView1" VerticalAlignment="Top" Width="120"

     VirtualizingStackPanel.IsVirtualizing="False"/><Button Content="ExpandTreeView" Height="23" HorizontalAlignment="Left" Margin="71,262,0,0" Name="button1" VerticalAlignment="Top" Width="120" Click="button1_Click" /></Grid></Window>
using System;
using System.Windows;
using System.Windows.Controls;
namespace WpfApplication13
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            LoadTestData(treeView1);
        }
        private void btnExpandTreeView_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ExpandTreeView(treeView1);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
       
        private static void LoadTestData(TreeView treeView)
        {
            for (int i = 0; i < 3; i++)
            {
                TreeViewItem newItem = new TreeViewItem();
                newItem.Header = DateTime.Now.ToLongTimeString();
                for (int j = 0; j < 100; j++)
                {
                    TreeViewItem newChildItem = new TreeViewItem();
                    newChildItem.Header = DateTime.Now.ToLongTimeString();
                    newItem.Items.Add(newChildItem);
                }
                treeView.Items.Add(newItem);
            }           
        }
        private static void ExpandTreeView(ItemsControl control)
        {
            foreach (object o in control.Items)
            {
                TreeViewItem item = (TreeViewItem)control.ItemContainerGenerator.ContainerFromItem(o);
                item.IsExpanded = true;
                ExpandTreeView(item);
            }
        }
    }
}

DataGridTemplateColumn can't update items source

$
0
0

I want to make "templated" column in DataGrid: one template should be used for numerous text columns, each of them binded to different fields in ItemsSource.

<Window x:Class="S3.CellTemplate"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:diag="clr-namespace:System.Diagnostics;assembly=WindowsBase"
        Height="450" Width="200" Loaded="loaded">
    <Window.Resources>
        <CollectionViewSource x:Key="data" />
    </Window.Resources>
    <Grid>
        <DataGrid HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch"
                  ItemsSource="{Binding Source={StaticResource data}}" AutoGenerateColumns="False">
            <DataGrid.Resources>
                <ControlTemplate x:Key="view" TargetType="DataGridCellsPresenter">
                    <TextBlock Text="{Binding DataContext, RelativeSource={RelativeSource TemplatedParent}}"/>
                </ControlTemplate>
                <ControlTemplate x:Key="edit" TargetType="DataGridCellsPresenter">
                    <TextBox Text="{Binding DataContext, RelativeSource={RelativeSource TemplatedParent},
                        diag:PresentationTraceSources.TraceLevel=High}"/>
                </ControlTemplate> 
            </DataGrid.Resources>
            <DataGrid.Columns>
                <DataGridTemplateColumn >
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <DataGridCellsPresenter Template="{StaticResource view}" DataContext="{Binding Path=Name}"/>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                    <DataGridTemplateColumn.CellEditingTemplate>
                        <DataTemplate>
                            <DataGridCellsPresenter Template="{StaticResource edit}" DataContext="{Binding Path=Name}"/>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellEditingTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>

public partial class CellTemplate : Window
{
    Entities ent = new Entities("name=" + Properties.Settings.Default.Connection);
        
    public CellTemplate()
    {
            InitializeComponent();
    }

    private void loaded(object sender, RoutedEventArgs e)
    {
        (this.FindResource("data") as CollectionViewSource).Source = (from u in ent.Unit orderby u.Name select u).ToList();
    }
}

It shows correct values in "view" and "edit" mode (so binding is not absolutely wrong), but it don't update items collection - when TextBox lost focus ItemsSource contains original values. What I am making wrong? 


What is going on with WPF?

$
0
0

There are quite a few questions on this forum about the status of WPF.  The most recent MS answer to "Is WPF Dead?" had 2 links to information to convince us that WPF is not dead.  Ironically both of those links were dead. The most recently published WPF book on Amazon was in 2014.  the last blog post by the WPF team at micrsoft was October 2015. there aren't even a dozen YouTube videos published in the last year on WPF.

Just what is the deal.  I need to make a decision on which desktop application development platform to use.  This is beyond ridiculous.

MR

How to bind multiple contents with the DataTemplate dynamically in WPF?

$
0
0

I want to create a TabItem with one ListBox and one WebBrowser type contents

inside it, which I want to create dynamically. I can able to add header part correctly,

but I dont know how to add multiple contents in DataTemplate.


Frustration with how much code is required in WPF to do the same thing in Angular/JS...

$
0
0

I have been a VB.Net/C#/WPF developer for a while now...

However, at work I started working on an Angular/JS web development portal and  am appalled with how little code is required to do things using this versus WPF...

Take for instance a simple button background color change when a mouse enters the field:

Here is sample code in WPF/XAML:

<Button Content="Button" HorizontalAlignment="Left" VerticalAlignment="Bottom" Width="50" Height="50" HorizontalContentAlignment="Left" BorderBrush="{x:Null}" Foreground="{x:Null}" Margin="50,0,0,0"><Button.Style><Style TargetType="{x:Type Button}"><Setter Property="Background" Value="Green"/><Setter Property="Template"><Setter.Value><ControlTemplate TargetType="{x:Type Button}"><Border Background="{TemplateBinding Background}"><ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/></Border></ControlTemplate></Setter.Value></Setter><Style.Triggers><Trigger Property="IsMouseOver" Value="True"><Setter Property="Background" Value="DarkGoldenrod"/></Trigger></Style.Triggers></Style></Button.Style></Button>


And here is the same code in Angular/JS:

<button ng-class="{red: hover}" ng-mouseenter="hover=!hover"ng-mouseleave="hover=!hover">ChangeColors</button>

with one line in the CSS file: 

.red {    background-color: red;}

I mean seriously?  Why is WPF THAT involved to do something SO simple? Then you are sitting there looking at the code trying to figure out exactly what it's doing...but anyone can look at that Angular/JS code and instantly know what its going to do even if they don't code...

I see why Angular/JS and various other libraries are taking over the world...they make coding FUN!  You can solve simple problems in 1 line of code instead of 22 lines of rubbish...

It's extremely disappointing WPF is so clunky with UI...I am almost tempted to start refactoring my WPF projects into Angular/JS projects using Edge.js and running them in the Chromium browser...for every 1 hour I code in Angular/JS I'm coding 3 hours in WPF...it just doesn't make sense anymore...

WPF C# Combobox NullReferenceException when selection changes again

$
0
0

I created a form in WPF (visual stutio 2013, C#) that allows the user to selected an item in the one combobox then in turn will open up text files and read a section of data in a text file that matches the combobox selection. The output goes to combobox2. the User will then select one item in this combobox which in turn opens and reads another text file data section and outputs to combobox3.

The program doesn't work properly. Here is the problem. If the user goes all the way through it is fine if and only if another selection in combobox1 is not made. If it is made an error is thrown.

The error reads " An unhandled exception of type 'System.NullReferenceException' occurred in WpfApplication3.exe......Additional information: Object reference not set to an instance of an object.

I don't know how to handle this. The program is to work regardless of how many times the user makes a selection.

Please give suggestions also. I am new to Xaml and C#. Thanks

Here is the C# code.

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.Collections.ObjectModel;

namespace WpfApplication3
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
///
public partial class MainWindow : Window
{
    public ObservableCollection<string> list = new   ObservableCollection<string>();
    public int selectedIndex = -1;
    public MainWindow()
    {
        InitializeComponent();
        list.Add("Los Angeles");
        list.Add("Boston");
        list.Add("Atlanta");
        this.CityList.ItemsSource = list;


   }
    public class HarCntyZip
    {
        public static List<string> lines = File.ReadLines(@"text1.txt").ToList();
    }

    public class StrbyZip
    {
        public static List<string> lines = File.ReadLines(@"text2.txt").ToList();
    }


    private void cityList_selectionChanged(object sender, SelectionChangedEventArgs e)
    {

        zip.Items.Clear();

        String getCityListSelItem = CityList.SelectedItem.ToString();
        var hczip = HarCntyZip.lines.IndexOf(getCityListSelItem);

        var g = hczip + 1;
        var j = 0;
        for (var i = 0; i < 300; i++){
            j = g + i;
            if (HarCntyZip.lines[j] == "")
            {
                break;
            }
            else if (HarCntyZip.lines[j] != "")
            {
                zip.Items.Add(HarCntyZip.lines[j]);
            }
        }

    }
    private void zip_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        StreetList.Items.Clear();


        String getZipSelItem = zip.SelectedItem.ToString();
        var Str = StrbyZip.lines.IndexOf(zip.SelectedItem.ToString());

        var s_l = Str + 1;
        var s_c = 0;
        for (var i = 0; i < 12000; i++)
        {
            s_c = s_l + i;
            if (StrbyZip.lines[s_c].ToString() == "")
            {
                break;
            }
            else if (StrbyZip.lines[s_c].ToString() != "")
            {
                StreetList.Items.Add(StrbyZip.lines[s_c].ToString());
            }
        }


    }

    private void StreetList_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {

    }


}
}

Here is the Xaml code

Window x:Class="WpfApplication3.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="683.1"><Grid><ComboBox HorizontalAlignment="Left" Height="22" Name="CityList" Margin="10,55,0,0" VerticalAlignment="Top" Width="140" SelectionChanged="CityList_selectionChanged"/><ComboBox  HorizontalAlignment="Left" Margin="232,55,0,0" VerticalAlignment="Top" Width="111" Name="zip" SelectionChanged="zip_SelectionChanged"/><ComboBox HorizontalAlignment="Left" Height="20" Margin="425,57,0,0" VerticalAlignment="Top" Width="181" Name="StreetList" SelectionChanged="StreetList_SelectionChanged"/></Grid>

text1.txt

Los Angeles
90005
90015

Boston
02120

Atlanta
30314
text2.txt
90005
Crenshaw Blvd
S Bronson Ave
W Norton Ave

90015
S Union Ave
W Pico Blvd
Venice Blvd

02120
Centre St
Washington St
Columbus Ave

30314
WestMoor Dr NW
Lena St NW
Temple St NW


ImageSource return by property

$
0
0

Hi all,

i want to image property bind in image control  and set image source using property .

How to return image source using by property .

Thanks,



A.Acharya Feedback to us Develop and promote your apps in Windows Store Please remember to mark the replies as answers if they help and unmark them if they provide no help.

WPF Ribbon Menue Problem

$
0
0

Hi,

I have a problem with disabling a menu item in a ribbonbar ...
If I disable the button is this defy with the mouse selectable !?

Here the XAML Code:

<RibbonGroup Header="Drucken Niederschriften"><RibbonMenuButton Label="Wahlniederschriften" x:Name="RIMBDRN"><RibbonButton Label="Briefwahlbezirk" x:Name="RIBTDRNBWBZ"  HorizontalAlignment="Left" /><RibbonButton Label="Urnenwahlbezirk" x:Name="RIBTDRNUWBZ"  HorizontalAlignment="Left"/><RibbonMenuButton Label="Gemeindewahlausschuß" x:Name="RIMBDRNGWA" ><RibbonButton Label="Test1"   x:Name="RIBTDRNKWART1" HorizontalAlignment="Left"/></RibbonMenuButton><RibbonMenuButton Label="Kreiswahlausschuß" x:Name="RIMBDRNKWA" HorizontalAlignment="Left"><RibbonButton Label="Test2"   x:Name="RIBTDRNKWART2" HorizontalAlignment="Left"/></RibbonMenuButton></RibbonMenuButton></RibbonGroup>

Have anyone an die how i can disable it so that the mouse can not focusble/selectable the Button!?

Best Regards

Bernd

WPF Grouping ListBox with Date on same line as Data

$
0
0

I have a ListBox that binds to a ListCollectionView called "Schedules".

<ListBox Grid.Row="2" ScrollViewer.HorizontalScrollBarVisibility="Disabled" ItemsSource="{Binding Schedules}"><ListBox.GroupStyle><GroupStyle><GroupStyle.HeaderTemplate><DataTemplate><TextBlock Text="{Binding Name}" /></DataTemplate></GroupStyle.HeaderTemplate></GroupStyle></ListBox.GroupStyle><ListBox.ItemTemplate><DataTemplate><StackPanel Background="Transparent"><Grid Background="Transparent"><Grid.ColumnDefinitions><ColumnDefinition  Width="100"/><ColumnDefinition  Width="100"/><ColumnDefinition/></Grid.ColumnDefinitions><Grid.RowDefinitions><RowDefinition/></Grid.RowDefinitions><!--I want my DateTime Grouping Here basically--><!--<TextBlock Grid.Column="0" Grid.Row="0"  Text="{Binding MyDateTime}" HorizontalAlignment="Left"  VerticalAlignment="Center"/>--><TextBlock Grid.Column="1" Grid.Row="0"  Text="{Binding MyDateTime, StringFormat='t'}" HorizontalAlignment="Left"  VerticalAlignment="Center"/><TextBlock Grid.Column="2" Grid.Row="0"  Text="{Binding SomeText}"  TextTrimming="WordEllipsis" LineStackingStrategy="MaxHeight" MaxHeight="20" HorizontalAlignment="Left"  VerticalAlignment="Center"/></Grid></StackPanel></DataTemplate></ListBox.ItemTemplate></ListBox>

And in my viewmodel I Group it by Date only (I use a ValueConverter that gives me back only a date:

Schedules.GroupDescriptions.Add(new PropertyGroupDescription("MyDateTime", new DateTimeToDateOnlyConverter()));

Is it possible to have the grouping but displaying it on the same line as the other data? Now you have a case where you get:

MyDateTime
-----------------Time | Sometext
-----------------Time | Sometext
-----------------Time | Sometext
MyDateTime2
-----------------Time | Sometext

I want it to display like this:

MyDateTime | Time | Sometext
                     | Time | Sometext
                     | Time | Sometext
MyDateTime | Time | Sometext
                     | Time | Sometext
                     | Time | Sometext




MetroTabItem View Going out of Scope

$
0
0

I have a MetroTabControl that I want to use to display several RDP connections using the TabItems, the problem that I`m having is, after I establish the first RDP connection, If I switch tabItem, the view goes out of scope and I loose the connection in that TabItem (so each time I switch tabitem the view goes out of scope). I wanted to maintain the connection alive in each TabItem and control the close of the view with the CloseTabCommand using the tabitem CloseButton.

In this sample the RemoteClients is an Observable collection of an objectClass that each TabItem will bind to 
e.g. ObservableCollection<RdpClient>RemoteClients{get; set;}
The SelectedRemoteClient represents the current selected object (RdpClient).
RemoteDesktopBaseControlView is the view that each TabItem will have and has all the bindings for the RdpClient object

 
<Grid><controls:MetroTabControl VerticalAlignment="Stretch" HorizontalAlignment="Stretch"
    							  IsSynchronizedWithCurrentItem="True"
    							  ItemsSource="{Binding RemoteClients, UpdateSourceTrigger=PropertyChanged}"
    							  SelectedItem="{Binding SelectedRemoteClient, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
    							  CloseTabCommand="{Binding CloseTabCommand}" ><controls:MetroTabControl.Resources><DataTemplate x:Key="contentTemplate" x:Shared="False"><RemoteDesktopBaseControlView /></DataTemplate></controls:MetroTabControl.Resources><controls:MetroTabControl.ItemContainerStyle><Style TargetType="{x:Type controls:MetroTabItem}"><Setter Property="Header" Value="{Binding Name, UpdateSourceTrigger=PropertyChanged}" /><Setter Property="controls:MetroTabItem.ContentTemplate" Value="{StaticResource contentTemplate}"/><Setter Property="controls:MetroTabItem.CloseButtonEnabled" Value="True"/><Setter Property="controls:MetroTabItem.CloseTabCommandParameter" Value="{Binding}" /><Setter Property="controls:ControlsHelper.HeaderFontSize" Value="16" /><Setter Property="controls:ControlsHelper.HeaderMargin" Value="4" /></Style></controls:MetroTabControl.ItemContainerStyle></controls:MetroTabControl></Grid>


Any Ideas how to fix this?


How To Show Selected Value in the combobox in wpf

$
0
0
We have generic list class as item source for example
   List<FuelType> fuelList = new List<FuelType>();

            fuelList.Add(new FuelType { RowNo = -1, FuelTypeName = "Select..." });
            fuelList.Add(new FuelType { RowNo = 0, FuelTypeName = "Diesel" });
            fuelList.Add(new FuelType { RowNo = 1, FuelTypeName = "Gas" });
            fuelList.Add(new FuelType { RowNo = 1, FuelTypeName = "Propane" });
            fuelList.Add(new FuelType { RowNo = 1, FuelTypeName = "NaturalL Gas" });
            fuelList.Add(new FuelType { RowNo = 1, FuelTypeName = "Dual Fuel" });
SiteSurveyModel.FuelTypeCollection = new ObservableCollectionEx<FuelType>(fuelList);

Here SiteSurveyModel.FuelTypeCollection is a item source and we are display member path is

DisplayMemberPath="FuelTypeName"

And We want to show selected combo box and we are using like as

SelectedValue="{Binding SiteSurveyModel.FuelType, Mode=TwoWay}"

or

SelectedValuePath="{Binding SiteSurveyModel.FuelType, Mode=TwoWay}"

or

SelectedItem="{Binding SiteSurveyModel.FuelType, Mode=TwoWay}"

And we are setting previous  value in the SiteSurveyModel.FuelType like as

 SiteSurveyModel.FuelType = BlankIfDbNull(dv[0]["fuelType"]) != string.Empty ? BlankIfDbNull(dv[0]["fuelType"]) : "Select..."

XAML of Combo box is

<ComboBox Grid.Row="0" Grid.Column="3" Name="fuelTypeComboBox"  Width="150" Height="30" StaysOpenOnEdit="True" IsSynchronizedWithCurrentItem="False"
                                    ItemsSource="{Binding SiteSurveyModel.FuelTypeCollection,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" VerticalAlignment="Top"
                                    DisplayMemberPath="FuelTypeName" SelectedValue="{Binding SiteSurveyModel.FuelType, Mode=TwoWay}"   IsEditable="True" IsTextSearchCaseSensitive="False"  Margin="5,0,0,0"><ie:Interaction.Triggers><ie:EventTrigger EventName="SelectionChanged"><ie:InvokeCommandAction Command="{Binding FuelTypeComboBoxSelectedItemChangedCommand}" CommandParameter="{Binding ElementName=fuelTypeComboBox}" ></ie:InvokeCommandAction></ie:EventTrigger></ie:Interaction.Triggers></ComboBox>

In my case combo box is not showing selected value. Why values is not showing as a selected ? Please Help me.

SiteSurveyModel.FuelType is a string type.

      public string FuelType
        {
            get { return _fuelType; }
            set
            {
                SetProperty(ref this._fuelType, value);
                RaisePropertyChanged("FuelType");
            }
        }

and Item Source Class is

  public class FuelType
    {
        private int? _rowNo = 0;
        private string  _fuelTypeName = string.Empty;
        public int? RowNo
        {
            get {return _rowNo;}
            set { _rowNo = value; }
        }
        public string FuelTypeName
        {
            get { return _fuelTypeName; }
            set { _fuelTypeName = value; }
        }
    }

Thanks.


Print from continuous “infinitely long” roll in WPF

$
0
0

I have the following piece of code:

var pdialog = new PrintDialog();

PageMediaSize size = new PageMediaSize(PageMediaSizeName.Unknown, number(_label.Settings.FullPaperWidth), number(_label.Settings.FullPaperHeight));

try
  {
  pdialog.PrintQueue = new PrintQueue(new PrintServer(), Properties.Settings.Default.PrinterName);
  pdialog.PrintQueue.CurrentJobSettings.CurrentPrintTicket.PageMediaSize = size;
   pdialog.PrintQueue.CurrentJobSettings.CurrentPrintTicket.PageMediaType = PageMediaType.Continuous;

  pdialog.PrintQueue.Commit();
  pdialog.PrintVisual(vis, "Label");
}
catch (Exception e)
  {
    MessageBoxResult result = MessageBox.Show(e.Message + "\n" + "Selecteer een andere printer", "Error!", MessageBoxButton.OK, MessageBoxImage.Warning, MessageBoxResult.OK);
  }
}

...

private float number(float numb){
    return numb / 25.4F * 96; //(converting millimeter to 1/96 inches)
}



Problem

As you can see, I put the PageMediaSize on Continuous since I will be printing on a continuous "infinitely long" roll, so I should be able to make infinitely long pages. However, the label printer stops to print at the same height as pdialog.PrintableAreaHeight and then cuts off the roll. How can I print pages that are longer than the default PrintableAreaHeight?

Edit

I got it working!! I'm able to print for example 15cm pages now at once withouth cutting the paper even though that is much longer than the default PrintableAreaHeight, which is what's supposed to happen. I changed PageMediaSizeName to Roll06Inch which did the job... but I wonder what the difference is! Why does Roll06Inch or Roll08Inch or any  of them work but "Unknown" doesn't? Doesn't make much sense to me! Hope someone can explain!





Pixel Shadder Clone

$
0
0

Hi all,

I'm getting an error from time to time, when i clone a instance of a ShaderEffect.

The error occurs in the line this.PixelShader = _pixelShader;.

After this i cannot apply the effect anymore, in order to work again i need to restart the application.

    public class AutoLEffect : ShaderEffect
    {
        private static PixelShader _pixelShader = new PixelShader() { UriSource = new Uri(@"pack://application:,,,/Effects;component/Effects/AutoLEffect.ps") };

        public AutoLEffect()
        {
            this.PixelShader = _pixelShader;

            UpdateShaderValue(InputProperty);
            UpdateShaderValue(TextureSizeProperty);
        }

        public static readonly DependencyProperty InputProperty = ShaderEffect.RegisterPixelShaderSamplerProperty("Input", typeof(AutoLEffect), 0);
        public Brush Input
        {
            get { return (Brush)GetValue(InputProperty); }
            set { SetValue(InputProperty, value); }
        }


        public static readonly DependencyProperty TextureSizeProperty = DependencyProperty.Register("TextureSize", typeof(Size), typeof(AutoLEffect), new UIPropertyMetadata(new Size(), PixelShaderConstantCallback(0)));
        public Size TextureSize
        {
            get { return (Size)GetValue(TextureSizeProperty); }
            set { SetValue(TextureSizeProperty, value); }
        }
    }

Creating a World Map

$
0
0

Hello,

I need to create or rather draw a World map using wpf and then display the flight traffic. I do not want to use bing maps or any third party map controls. How do I accomplish this?

I want to draw a raw map on screen using geographical coordinates for land and sea.

Regards,

Amarnath Katti

Viewing all 18858 articles
Browse latest View live


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