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

Strange Error on DataTrigger

$
0
0
Trigger newbie here, here's what I was trying:

        <Style x:Key="RedOnFailure"
            <Style.Triggers> 
                <DataTrigger Binding="{Path=DataContext.NumFailures, RelativeSource={RelativeSource TemplatedParent}}" Value="True"
                    <Setter Property="DataTemplate.Background" Value="Red"/> 
                </DataTrigger> 
            </Style.Triggers> 
        </Style> 
 


And I get the following error:

error MC1000: Unknown build error, 'Index (zero based) must be greater than or equal to zero and less than the size of the argument list. Line 166 Position 30.'

I couldn't find any information about that error.  Thanks!

Can Datagrid row be populated with data at design time?

$
0
0

I've been populating WPF DataGrid by creating a class with relevant properties in the code behind. Or using binding to get values from an xml file.

Can I populate WPF DataGrid during design time?

Highlighted text in the following code gives an idea of how I want to create some static data in the design time.

<DataGrid HorizontalAlignment="Left" Margin="84,57,0,0" VerticalAlignment="Top" Height="183" Width="346" AutoGenerateColumns="False">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Column1"></DataGridTextColumn>
                <DataGridTextColumn Header="Column2"></DataGridTextColumn>
                <DataGridTextColumn Header="Column3"></DataGridTextColumn>
            </DataGrid.Columns>

            <DataGrid.Rows><o:p></o:p>

              <DataGridRow Column1="Aaaa" Column2="Bbbb" Column3="Cccc"></DataGridRow><o:p></o:p>

             <DataGridRow Column1="Dddd" Column2="Eeee" Column3="Ffff"></DataGridRow><o:p></o:p>

 </DataGrid.Rows>

</DataGrid>

Thank you.

Harika


What is the Zeitgeist of creating and printing simple Documents in WPF?

$
0
0

I need to create a few documents that just have some of their text replaced by text from properties in the program, the final result presented to the user, printed mainly in A4 paper and  exported to a common document format. 

I have those documents ready in Word and its supported formats. I do not have requirements for lightning speed though I want them previewed in the software without Word.

I wonder what are the best technologies at the moment. Am I required to write them from the start in XAML? Can I view an .rtf in WPF but also replace some of its text?

PS. The most advanced feature of those documents are a Table or two. Even pictures are rare. Text is only alternating in size and font weight.

PPS. They need to be able to be saved in .pdf and either .rtf or .doc or docx.







Join two or more files

$
0
0

hi developer,

I am written multiple open dialog box in wpf as below:

 string[] inputFile = null;
        private void btnOpenFiles_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Multiselect = true;
            openFileDialog.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
            if (openFileDialog.ShowDialog() == true)
            {
                inputFile = openFileDialog.FileNames;
                foreach (string filename in inputFile)
                    lbFiles.Items.Add(System.IO.Path.GetFileName(filename));
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            foreach (var files in inputFile)
            {
                string line = null;
                line = string.Join(",",lbFiles.Items);
                MessageBox.Show(line);

            }
        }

How to join two or more files in Button_Click function or method? e.g aa.txt, bb.txt, cc.txt
Any Idea?

I am waiting for your response

Thanks


Change Windows 8 Lockscreen image with wpf/service only works once

$
0
0

I'm trying to Change the lockscreenimage with a service. But it only works once. If I try it a second time (i attached a timestamp text to the Image with drawtext), the new Image is shown correctly in the Settings pane inside the lockscreen Settings Dialog but is not shown on the lockscreen itself.

Are there some known restrictions?

I followed These steps here: http://www.codeproject.com/Questions/709599/Csharp-code-to-change-lockscreen-and-assign-file-t
and here: http://stackoverflow.com/questions/20103561/wpf-application-incorporating-winapi-win8-components

Then I've Access to the needed assamblies and able to call await LockScreen.SetImageFileAsync(imageFile);

As said... works fine the first time, but Fails the second.
I tried to run the code as a service, as a console applicationd and as aregular wpf application.

FBX 3D Scene in WPF App?

$
0
0

Hello, If I create a Winforms app in VS2013 then I can add a 3D graphics (fbx) scene no problem. What I want to do is put the scene into  a WPF Main Window (or an MDI parent-child). Can anyone tell me if this is possible, and if so the bet way? I have a 3D CAD model that I want to load as a resource. I also want to allow user input via a linked dialog and save a file of these settings.

Many thanks in advance for any help

Mick

User Control MVVM guidance

$
0
0

Hi,

I would like some guidance on how to use a WPF User Control which wraps a combo box using MVVM in the following scenario.

In Windows forms I tend to use User Controls liberally and in the case above say where I have a combo box for products look-up when a product is selected, I expose the selected item changed event in the User Control so the form using it can then detect a change and for example do some related work such as look up product orders.

In WPF using MVVM I am not sure how to implement the above scenario. The User Control has a view model and so does a window hosting the User Control. How do I update the window's view model with the selected item or selected value (from the combo box) in the user control?

Currently I am not using any tool kits such as Prism or MVVM light.

Marinos.

How to validate in the set of a property binded to TextBox

$
0
0

Hi All,

I was trying to validate the text entered in a textbox in the set of the property binded to it and was trying to stop the user on some special characters like * / etc. The text set to the property after validation is not reflecting in the UI. Below is the property and the xaml part of it. Looking forward for some help

private string text = string.Empty;
        public string Text
        {
            get
            {
                return this.text;
            }

            set
            {
                if (value.Contains("*"))
                {
                    this.text = value.Trim('*');
                }

                else
                {
                    this.text = value;
                }
                this.OnPropertyChanged("Text");
            }
        }
        <TextBox Margin="10"
                 Grid.Row="0"
                 Text="{Binding Text, UpdateSourceTrigger=PropertyChanged}">



Ramakrishna




Change combobox itemssource using style and triggers?

$
0
0

Hi All,

Is it possible to change ItemsSource using style and triggers? I have three comboboxes. With first one, user should define if he is doing 'Process' activity or 'Non-Process' activity. Then if he pickup 'Process' bind to 'ProcessActivities' property else if 'Non-Process' bind it to 'NonProcess'. Now, I'm doing this with:

SelectedValue="{Binding EmployeeViewM.NonProc, Mode=OneWayToSource}" SelectedValuePath="Tag"

Depends on Tag, I'm executing proper RelayCommand to populate Second combobox.

I was wondering, if it's possible to set itemssource for the second combobox in xaml depending on value from the first one?

Is there something similar to this?:

<ContentControl.Style><Style TargetType="{x:Type ContentControl}"><Style.Triggers><DataTrigger Binding="{Binding LoginViewM.Content, Source={StaticResource Locator}}" Value="False"><Setter Property="Content"><Setter.Value><EE:EmployeeViewModel/></Setter.Value></Setter></DataTrigger><DataTrigger Binding="{Binding LoginViewM.Content, Source={StaticResource Locator}}" Value="True"><Setter Property="Content"><Setter.Value><MG:ManagementViewModel/></Setter.Value></Setter></DataTrigger></Style.Triggers></Style></ContentControl.Style>

It is for my MainWindow to pick up correct view. Maybe for combobox I could implement something similar?

Thank you for any suggestions

Adornor - ArrangeOverride() is not called for Line when line is moved out of the parent rectangle using arrow keys

$
0
0

Hi,

i am facing problem when moving line object using arrow keys.

Line adornor thumb points when line inside parent rectangle

ArrangeOverride() method of Adornor is called when the line is inside its parent rectangle. But when the line goes out of parent rectangle, ArrangeOverride() is not called. Because of this, the thumb points are not place perfectly on line.

thumb points when line out of parent rectangle

And also this issue occurs when line moved above the parent. Even moving below the rectangle works fine.

Please suggest me some solution. i am not able to figure out who is calling these methods as these are simply external codes in call stack

Windows 10: WPF Window with WindowStyle="None" and ResizeMode="CanResize" is showing white bar on top of window

$
0
0

I like to create a WPF window which has no border at all and which is resizeable. With previous versions of Windows this used to be quite simple, you just had to use WindowStyle="None" and ResizeMode="CanResize" as given in the following xaml:

<Windowx:Class="WpfApplication1.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"ResizeMode="CanResize"

     WindowStyle="None"Background="#FF0000">

   <Grid>

   </Grid>

</Window>

With Windows 10 this is not working any more as a white top bar is always displayed:

First of all I would expect that no white bar is given when I request a border less window.

Secondly is there a work around to get rid of the white top bar?

NOTE: When I set the ResizeMode to 'NoResize' the white top bar disappears.

Thanks a lot in advance

NOTE: This is a cross post fromhttp://answers.microsoft.com/en-us/insider/forum/insider_wintp-insider_desktop/wpf-window-with-windowstylenone-and/96659722-b088-4cf6-9e6f-2500ea3bab8e (as suggested by the Windows Insider Preview Community).

Binding Property to ContentControl.

$
0
0

Hi,

I have a UserControl say MyDialog and it has got a property as shown below,

public static readonly DependencyProperty OpenInWordStyleProperty =
            DependencyProperty.Register("OpenInWordStyle", typeof(MyDocumentExtensionType),
            typeof(MyDialog), new PropertyMetadata(MyDocumentExtensionType.WordDocumentStyle, new PropertyChangedCallback(OnChanged)));
        private static void OnChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            MyDialog dialog = d as MyDialog ;
            ViewModel.MyViewModel viewModel = dialog.DataContext as ViewModel.MyViewModel;
            viewModel.SetOpenInWordToggleButtonStyle(dialog.OpenInWordStyle.ToString());
        }
        // Property wrapper
        public MyDocumentExtensionType OpenInWordStyle
        {
            get
            {
                return (MyDocumentExtensionType)GetValue(OpenInWordStyleProperty);
            }
            set
            {
                SetValue(OpenInWordStyleProperty, value);
            }
        }

Now i want to set the above 'OpenInWordStyle' property from my other UserControl say 'MyParentDialog', MyParentDialog has a Listbox and its Itemtemplate is as shown below,

<ListBox.ItemTemplate><DataTemplate><Expander DataContext="{Binding}" Style="{DynamicResource MyDocExpanderStyle}" Header="{Binding DocumentName}"
                                              IsExpanded="{Binding IsNodeExpanded, Mode=OneTime}" Expanded="myDocExpander_Expanded" ><ItemsControl ItemsSource="{Binding Files}" Background="White" ><ItemsControl.ItemTemplate><DataTemplate><Grid Margin="20,2,8,2" x:Name="DocumentNameGrid"><Grid.ColumnDefinitions><ColumnDefinition Width="*" /><ColumnDefinition Width="Auto"/></Grid.ColumnDefinitions><TextBlock x:Name="DocumentNameTextBlock" Background="White" Style="{StaticResource PracticeAreasTitleStyleArial}"><Run Text="{Binding NameOfDocument, IsAsync=True}"/><Run Text="{Binding DocumentExtension}"/></TextBlock><Border Grid.Column="1" x:Name="OpenInWordBorder" Margin="2"><ContentControl DataContext="{Binding DocumentExtension}"  ContentTemplate="{StaticResource MyToggleButtonTemplate}"/></Border></Grid></DataTemplate></ItemsControl.ItemTemplate></ItemsControl></Expander></DataTemplate></ListBox.ItemTemplate>

In ContentControl's ContentTemplate i am calling 'MyDialog' usercontrol and binding the 'OpenInWordStyle' property. as shown below,

<DataTemplate x:Key="MyToggleButtonTemplate"><MyControls:MyDialog x:Name="MyDialog" OpenInWordStyle="{Binding DocumentExtension}" Grid.Column="1" Margin="2"
                                                            HorizontalAlignment="Stretch"  VerticalAlignment="Center"  ><MyControls:MyDialog.CommandBindings><CommandBinding  Command="{x:Static MyControls:MyDialogCommands.SelectedTemplateChangeCommand}" Executed="MySelectedItemChangedCommandBinding_Executed"/><CommandBinding Command="Save" Executed="MyDialogShowCommandBinding_Executed" CanExecute="MyDialogShowCommandCanExecuteBinding_Executed" /><CommandBinding Command="{x:Static MyControls:MyDialogCommands.MoreButtonClickCommand}" Executed="MyDialogMoreButtonClickCommandBinding_Executed"/><MyControls:MyDialog.CommandBindings></MyControls:MyDialog></DataTemplate>

Please help me out how i can bind 'DocumentExtension' property of MyParentDialog to 'OpenInWordStyle' property of MyDialog.

Regards,


Chetan Rajakumar

Meets or not the MVVM pattern?

$
0
0

hello,

to enable/disable command in MainViewModel I'm using a property into another VM, selectPage.ConfigParams.......

Is correct this to MVVM pattern ?

// MainViewModel commands ...

private bool AddParamCommandCanExecute()
{
return selectedPage != null && selectedPage.ConfigParams.Count < 30;
}

Another similar question about MVVM pattern:

in MainViewModel I've a command called "New". Is correct that in this command "clear" one collection that is in binding of my UserControl (coded as another ViewModel) ?

thanks

How do I intercept a PageDown keyboard entry?

$
0
0

To intercept keyboard entries:

    <RichTextBox HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
        <RichTextBox.InputBindings>
            <KeyBinding Key="T" Modifiers="Control" Command="ApplicationCommands.NotACommand" />
            <KeyBinding Key="PageDown" Command="ApplicationCommands.NotACommand" />
        </RichTextBox.InputBindings>
    </RichTextBox>

    private void Window_KeyDown(object sender, KeyEventArgs e)
    {
        if (System.Windows.Input.Keyboard.Modifiers == (System.Windows.Input.ModifierKeys.Control) && e.Key == System.Windows.Input.Key.T) {
            e.Handled = true;
            ...
        }
        else if (Key.PageDown {
            e.Handled = true;
            ...
        }
    }

The ctrl-T is intercepted.  The PageDown is not.


bhs67

.Net framework 4.5.1 not allowing build action of an image file as 'Splash screen'

$
0
0

Hello,

We had a WPF application built in .Net framework 4.0 . There was an image file (.BMP) whose built action property was set as 'splash screen' and that image was working as a splash screen on application start up. Now we have upgraded application to .Net framework 4.5.1 and post upgradation we are getting a build error stating that target .Net framework doesn't support the build action of that image file as 'splash screen'. The build passes locally but when we build it on continuous integration environment it fails. Can some one please help how we can remove this build error?

Thanks.


Wpf Application Icon

$
0
0

Hello.

    I'm struggling to make a icon that suits nice into my wpf application. The problem stands with the size of the icon itself.

I've read this. And creating a icon of 48X48px and adding it to the solution like this.

The result was 

  

Clearly the result was acceptable for the desktop icon but the taskbar icon is kinda like Sh*t.

Am I doing it wrong? Is there a way of add different size icons and the app selects the proper one?

Other apps look nice like skype. If I press Crtrl + + and scroll up the size of the skype icon is allways perfect. 

How to do something like that? Any ideas?


-- Jorge_M_P

DocumentPaginator: GetPage calls function that creates a datagrid in each page but datagrid shows no data?

$
0
0

Hi all,

I was using the code from http://tech.pro/tutorial/888/wpf-printing-part-2-pagination to create a paginator but I found it too hard to align the columns I had. I was playing with creating an xps document a while back and that project had a function that creates the page with a datagrid. It works in the xps project so I thought to add the function (CreatePage) to the paginator GetPage function and see if it worked.
I was very surprised that it worked ... well ... almost. I have dummy values for the datagrid in CreatePage. I'm writing the document to the pdf writter for testing. I can see the datagrid (headers and background colors in the rows) in the page but for some reason I don't  understand it shows no content in the cells. I'm no expert at this so I thought I had to set the brush for the datagrid to black but that didn't do  anything.

I'm wondering if what I'm doing is right and why I can not see any text in the datagrid once in the pdf page?

Thanks

Here is the code:

    public class DataItem1
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string EmployeeNumber { get; set; }
        public string backgroundColor { get; set; }
    }


    public class PaginatorCode : DocumentPaginator
    {
        private List<displayedData> _rowDataToPrint = new List<displayedData>();
        private List<double> _columnsWidths = new List<double>();
        private Size _PageSize;

        private int _numberOfRowsToPrint;
        private int _RowsPerPage;

        public PaginatorCode(List<displayedData> rowsToPrint, List<double> columnsWidths, Size pageSize)
        {
            _rowDataToPrint.AddRange(rowsToPrint);
            _numberOfRowsToPrint = rowsToPrint.Count;
            _columnsWidths.AddRange(columnsWidths);

            PageSize = pageSize;    //this calls the method PageSize (set) defined below. "_PageSize" is init there.
        }

        public override DocumentPage GetPage(int pageNumber)
        {
            int currentRow = _RowsPerPage * pageNumber;


            var page = CreatePage(currentRow, _rowDataToPrint);


            page.Measure(PageSize);
            page.Arrange(new Rect(new Point(0, 0), PageSize));

            return new DocumentPage(page);
        }

        public override bool IsPageCountValid
        {
            get { return true; }
        }

        public override int PageCount
        {
            get { return (int)Math.Ceiling(_numberOfRowsToPrint / (double)_RowsPerPage); }
        }

        public override Size PageSize
        {
            get
            {
                return _PageSize;
            }
            set
            {
                _PageSize = value;
                _RowsPerPage = PageElement.RowsPerPage(PageSize.Height);
                if (_RowsPerPage <= 0)
                    throw new InvalidOperationException("_RowsPerPage <= 0");
            }
        }

        public override IDocumentPaginatorSource Source
        {
            get { return null; }
        }


        //---------------------------

        public FixedPage CreatePage(int currentRow, List<displayedData> rows)
        {

            FixedPage fp = new FixedPage();
            //fp.Width = 1056;    // 11   landscape
            fp.Width = PageSize.Width;
            //fp.Height = 816;    // 8.5
            fp.Height = PageSize.Height;
            fp.Margin = new Thickness(25, 25, 25, 25);

            Canvas g = new Canvas();
            g.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
            g.VerticalAlignment = System.Windows.VerticalAlignment.Center;
            fp.Children.Add(g);

            DataGrid myDatagrid = new DataGrid();
            myDatagrid.RowHeaderWidth = 0;
            myDatagrid.GridLinesVisibility = System.Windows.Controls.DataGridGridLinesVisibility.None;
            myDatagrid.BorderThickness = new Thickness(0, 0, 0, 0);    //left, top, right, bottom
            myDatagrid.FontWeight = FontWeights.Bold;
            //myDatagrid.Foreground = Brushes.Black; <----- this had no effect

            Style backgroundColorStyle = new Style();

            //---backgroundColorWhite
            backgroundColorStyle.TargetType = typeof(DataGridRow);
            DataTrigger setWhite = new DataTrigger();
            setWhite.Binding = new Binding("backgroundColor");
            setWhite.Value = "White";
            setWhite.Setters.Add(new Setter(DataGridRow.BackgroundProperty, Brushes.White));
            backgroundColorStyle.Triggers.Add(setWhite);

            //---backgroundColorBlanchedAlmond
            backgroundColorStyle.TargetType = typeof(DataGridRow);
            DataTrigger setBlanchedAlmond = new DataTrigger();
            setBlanchedAlmond.Binding = new Binding("backgroundColor");
            setBlanchedAlmond.Value = "BlanchedAlmond";
            setBlanchedAlmond.Setters.Add(new Setter(DataGridRow.BackgroundProperty, Brushes.BlanchedAlmond));
            backgroundColorStyle.Triggers.Add(setBlanchedAlmond );


            myDatagrid.ItemContainerStyle = backgroundColorStyle;


            DataGridTextColumn textColumn1 = new DataGridTextColumn();
            textColumn1.Header = "First Name";
            textColumn1.FontWeight = FontWeights.Regular;
            textColumn1.Width = 100;
            textColumn1.Binding = new Binding("FirstName");
            myDatagrid.Columns.Add(textColumn1);

            DataGridTextColumn textColumn2 = new DataGridTextColumn();
            textColumn2.Header = "Last Name";
            textColumn2.FontWeight = FontWeights.Regular;
            textColumn2.Width = 100;
            textColumn2.Binding = new Binding("LastName");
            myDatagrid.Columns.Add(textColumn2);

            DataGridTextColumn textColumn3 = new DataGridTextColumn();
            textColumn3.Header = "Employee No.";
            textColumn3.FontWeight = FontWeights.Regular;
            textColumn3.Width = 100;
            textColumn3.Binding = new Binding("EmployeeNumber");
            myDatagrid.Columns.Add(textColumn3);


            myDatagrid.Items.Add(new DataItem1 { FirstName = "John", LastName = "Smith", EmployeeNumber = "2551", backgroundColor = "BlanchedAlmond" });
            myDatagrid.Items.Add(new DataItem1 { FirstName = "Rod", LastName = "Click", EmployeeNumber = "2691", backgroundColor = "White" });
            myDatagrid.Items.Add(new DataItem1 { FirstName = "Peter", LastName = "abcdfSmith", EmployeeNumber = "0259", backgroundColor = "BlanchedAlmond" });

            g.Children.Add(myDatagrid);

            return fp;

        }

    }


WPF Datagrid: Set DataGrid / DataSource to Max 4 records

$
0
0

Is there a way to set grid or datasource to 4 max records always always. So if a user delete a row, the grid should always show 4 rows or 4 records.

Color ID   Color

1              red

2              blue

3              green

4              yellow

If user delete record colored 4, the results should be

Color ID   Color

1              red

2              blue

3              green

5               ""





WPF Datagrid: EmptyRows to True

$
0
0

How to set the WPF datagrid to emptys to true? I want to always have empty rows in the datagrid. Is there away. At the moment, I have the datasource bind to my itemsource.

Binding error with ElementName in UserControl, why?

$
0
0

I'm getting a binding error "Cannot find source for binding with reference 'ElementName=SearchBox'" on a binding inside a UserControl. If the UserControl is contained in a Frame element, then all is fine, but if the UserControl is either contained in a ContentControl or defined by itself, then the error occurs.

Any ideas how to solve this problem?

Code:

<Page x:Class="WpfBrowserApplication1.Page1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:l="clr-namespace:WpfBrowserApplication1"><StackPanel><UserControl Name="ContentHost" /><Frame Name="ContentFrame" /><!-- Gives BindingExpression error: --><l:ContentPage /></StackPanel></Page>

 

namespace WpfBrowserApplication1
{
    using System.Windows;
    using System.Windows.Controls;
    public partial class Page1 : Page
    {
        public Page1()
        {
            InitializeComponent();
            Loaded += (sender, args) =>
            {
                // Ok
                ContentFrame.Content = new ContentPage();
                // Gives binding expression error:
                ContentHost.Content = new ContentPage();
                /* System.Windows.Data Error: 4 : Cannot find source for binding with reference 'ElementName=SearchBox'. BindingExpression:(no path); DataItem=null; target element is 'ContentPage' (Name=''); target property is 'FocusedElement' (type 'IInputElement') */
            };
        }
    }
}

 

<UserControl x:Class="WpfBrowserApplication1.ContentPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    FocusManager.FocusedElement="{Binding ElementName=SearchBox}"><StackPanel><TextBox /><TextBox Name="SearchBox" Text="Hello" /><TextBox /></StackPanel></UserControl>

Tor Langlo, Koda Software
Viewing all 18858 articles
Browse latest View live


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