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

Make Enter On A Button Act As Mouse Click. Please Help!

$
0
0

Hi there all,

I have my program set up so as that when i press enter it tabs between all the textboxes on the usercontrol. i am wanting it though, so that when it lands on a button and i press enter, it acts like a previewmouseleftbutton up event. is it possible to do this? i have multiple buttons on the form so i cant use the default button property.When i press enter the previewmouseleftbutton event must be called without having to create a new handler.

Any help would be greatly appreciated.


james


Many to Many (Students , classes example) Datagrid xaml binding

$
0
0

I have a WPF / entity framework application, my model have student , class entities there is a many to many association/relation between student and class (student can have many classes and class have many students )

student [ Id ,Name , Classes(Navigation property) ] classes [ Id ,Title, Students(Navigation property ]

in this case the entity framework don't show the join/relation table.

i have a 2 DataGirds as master details, student grid is the master and classes is details

how can i set the binding to classes gird (the details gird) so i can add and remove classes to the selected student?

what i want is to select a student from the master grid and add or remove his classes

this is my classes gird

<DataGrid x:Name="classesDataGrid"
                      AutoGenerateColumns="False"
                      EnableRowVirtualization="True"
                      Height="200"
                      ItemsSource="{Binding Source={StaticResource studentClassesViewSource}}"
                      RowDetailsVisibilityMode="VisibleWhenSelected"
                      Width="380"><DataGrid.Columns><DataGridComboBoxColumn Header="Class Name From Combo"
                                            Width="*"

                                            ItemsSource="{Binding Source={StaticResource classViewSource}}" 
                                            DisplayMemberPath="Name"

                                            SelectedItemBinding="{Binding Students}" 

                                            /><!--<DataGridTextColumn x:Name="durationColumn"
                                        Binding="{Binding Duration}"
                                        Header="Duration"
                                        Width="SizeToHeader" />--></DataGrid.Columns>

This scenario works fine when the relation is one to many but i couldn't make it work for many to many relations .

I've found a similar post on this problem on msdn, but the conclusion that this scenario can't be done (in datagrid at least).


WPF Application using EF 5 and SqlCe 4 - create, deploy and migrate

$
0
0

Hi,

I have to create a distributed WPF application with a flat database on client side in order to work offline if the WCF service is not reachable. 

I thought about using entity framework model first approach, mapped to a dummy sqlce-database file. Then I would customize the whole mapping thing the way that a user-related sqlce-database-file is created on client side executing a bunch of create-table commands for the first usage. Read and write would happen through Linq to Entity.  

Later, with every release,  I would ship a sql-file which updates the existing user-database. 

What I've got so far is the automatic generated .sqlce file when using "create database from model". I can modify this file, add it to the properties resouces of the assembly and execute the sql statements. I create a database file with user related filename, I can insert, update and delete using normal ado.net.

What I don't get is the mapping to the entity framework context to use linq to entity instead of sql statements.

I read about "SqlCeConnectionFactory" and the method SetInitializer() but I don't understand how to use it properly. Simply because I don't think that changing the automatically created context class that inherits from DbContext is the right way. 

Can anybody give me some hints, advices, code snippets, links etc... that could solve my problem? 

Maybe I am also totally wrong and there is a better way to get what I want?

Thanks.

How do I set a column in WPF datagrid as percentage value with 2 decimal points?

$
0
0

How do I set a column in WPF datagrid as percentage value with 2 decimal points?

Here is my declaration of the data grid in XAML:

<DataGrid

             ItemsSource="{Binding}" AutoGenerateColumns="True" IsReadOnly="False" IsEnabled="True"

                x:Name="dg_MyDataGrid" CanUserAddRows="False" SelectionMode="Extended" SelectionUnit="FullRow"

                CanUserSortColumns="true" CanUserDeleteRows="False" AlternatingRowBackground="AliceBlue" Margin="0,252,0,23"

             ColumnWidth="120">

           

           

       </DataGrid>

I am dynamically binding my column in the backend C# code in one of the events as follows:

//declaration of list of custom created data type ParameterValues

List<ParameterValues> GridParameterValues;

//… some code to load the list…

//binding the list to the data grid

dg_MyDataGrid.ItemsSource = GridParameterValues;

Now my requirement is I need 4<sup>th</sup> and 7<sup>th</sup> columns to have a format such as “8.20%” instead it is showing up as 0.082

Is there any way we could automatically convert all values in a particular column which has values like 0.082 to display as “8.20 %”. I also have the requirement to display the value as “8.20 %” instead of “8.2 %”.

I really appreciate your advice!

How can i display controls faster which is added run time?

$
0
0

Hi,

I have a one form and I try to display data in DataGrid control with 100,000 rows & 10 columns and filling grid from DataTable. It works fine. I try to display data in TextBlock and adding TextBlock in StackPanel. But it takes to much time to display while DataGrid is faster. What kind of improvement I required in my code.

Here code is displayed.

///// Designing<Window x:Class="ToolBarApp.frmSearch"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    WindowStartupLocation="CenterScreen"
    Title="frmSearch" Height="500" Width="500" ><Grid><ScrollViewer><StackPanel Name="ctl_Display"></StackPanel></ScrollViewer></Grid></Window>

//// Constructor

public frmSearch(bool AddToGrid, DataTable _dt)
        {
            InitializeComponent();

            if (AddToGrid)
            {
                DataGrid _dg = new DataGrid();
                _dg.Height = 450;
                _dg.Width = 450;
                _dg.AutoGenerateColumns = true;
                _dg.ItemsSource = _dt.DefaultView;
                ctl_Display.Children.Add(_dg);
            }
            else
            {
                TextBlock _TextBlock;

                foreach (DataRow _DR in _dt.Rows)
                {

                    _TextBlock = new TextBlock();
                    _TextBlock.Margin = new Thickness(0);
                    _TextBlock.FontSize = 14;
                    _TextBlock.Foreground = Brushes.White;
                    _TextBlock.Text = _DR["Item_Name"].ToString();
                    ctl_Display.Children.Add(_TextBlock);
                }
            }
        }


SQL Server Report Viewer Control , Replacing Toolbar with own WPF Controls

$
0
0

Dear all;

i am using VS2010 and SQL Server Express 2008R2 express 

i have integrated the original Report Viewer Control in my WPF application by using an windows form host.

The Reportviewer works fine so far but i wan't to hide the standard toolbar and access the functions to navigate tru the report

by customs controls.

Unfortunately i haven't find the methods in the report viewer api to do so.

Does some one have an example how to navigate true the displayed report with own controls (simplest example: with buttons

from the VS2010 toolbar).

Thanks in adcance

 

Record Screen | WPF, DirectX| Camtasia

$
0
0

Hi,

I want to build a screen recorder which will record on screen activity like "Camtasia"...

Please let me know do I need to use WPF or Direct X for it

Please provide detail if anyone has done it in the past 

Suggestion how to localize templates XAML

$
0
0

Hi,

my application is composed by a main window which loads in its client area different XAML for different customers.
The directory structure of the program is:

MyProgram
     |- Templates
              |- Customer A
              |- Customer B

in the Customer folders there is the XAML file to load dynamically.
Now, which is the best way to localize the XAML without to touch the main application?

I don't want to store the strings into the application resource file because I don't want to rebuild it every time I have to made a change to a customer GUI.

Thanks in advance for the suggestions!

Daniele.


Create Custom Calendar Using Datagrid

$
0
0

Hello everyone,

I need help in creating a custom calendar using datagrid in WPF.

Please give me some suggestions or samples... 

Strange problem with RenderTargetBitmap

$
0
0

I am developing a frame extract from video program.  It works well and I can set an interval for the screenshots which are the stored in individual jpg files.

Now I am adding the ability to add things like titles to those jpgs.  I have an architecture which creates a TitleEffect which has things like the text, fontsize, color and a in/out point.  Now comes the problem.

My first go round is basically - if there is an effect on the video I am extracting frames from then it calls a function within the TitleEffect class which checks the in/out time and if the position of the video falls within those times it returns a usercontrol which can be added to the children of  the Grid which I am using as the basis for the screen capture.  Again this works well and I can see the title appear when it should and disappear when it should.

Now the problem.  While I can see the title in the window showing the video while doing the frame captures, the resulting jpg does not show the title.  If I put the usercontrol into my window thru XAML and rather than add the control in code just set the datacontext, again I see the title and the jpg shows the title.

I have used Snoop to look at the visual tree and both methods result in the same entries in the tree.

The reason I am trying to do it the code way is that I want to be able to have many different types of effects all using the same architecture.  With the present problem that is not feasible.

The code I am using to add the usercontrol in code is:

        If currentFileBeingCaptured.Effects.Count > 0 Then

            Dim af As AddedEffect = CType(currentFileBeingCaptured.Effects(0), AddedEffect)
            Dim tmp As UserControl = af.GetUIElement(theMediaPlayer.Position)
            If tmp IsNot Nothing Then
                If Not useCurrent Then
                    If OverLayGrid.Children.Count > 0 Then
                        OverLayGrid.Children.RemoveAt(0)
                    End If
                    tmp.DataContext = af
                    OverLayGrid.Children.Add(tmp)
                Else
                    testUC.DataContext = af
                End If
                overlayadded = True
            End If
        End If

In the above code useCurrent is a variable I created just for testing.  True uses the control already existing in the XAML and false will take the usercontrol passed back from the GetUIElement.  If I am using the generated usercontrol I check the count of children in the grid named OverLayGrid and if it is larger than zero (the XAML based usercontrol) it removes it.

As I said above the resulting visual tree is identical in both cases with the only difference being that the XAML based usercontrol has a name.

Any help would be great as I have tried about every permutation I can think of to fix this problem but none has worked.

TIA

Lloyd Sheen

  BTW the XAML for the VisualGrid is:

<Grid x:Name="VisualGrid" Grid.Row="1"
                          Width="{Binding ElementName=sizeCombo, Path=SelectedItem.width, Converter={StaticResource dummyConverter}}" 
                          Height="{Binding ElementName=sizeCombo, Path=SelectedItem.height, Converter={StaticResource dummyConverter}}"><MediaElement x:Name="theMediaPlayer" ScrubbingEnabled="True" 
                              Visibility="Visible" 
                              LoadedBehavior="Manual" 
                              Loaded="MediaElement_Loaded"  
                              MediaOpened="theMediaPlayer_MediaOpened" 
                              Margin="0,5"></MediaElement><Grid x:Name="OverLayGrid"><local:TitleEffectUC x:Name="testUC" Visibility="Visible"></local:TitleEffectUC></Grid></Grid>


Lloyd Sheen


CommandBinding doesn't work

$
0
0

hi,

Just trying to call a Command from one MenuItem:

XAML:

<Window.CommandBindings><CommandBinding Command="ApplicationCommands.Close" Executed="OnClose"/></Window.CommandBindings><MenuItem Name="Contextual_Salir" Header="Salir" Visibility="Visible"  Command="ApplicationCommands.Close"><MenuItem.Icon><Image Source="/Imagenes/Mapa_de_procesos.png" Height="20" Width="20"/></MenuItem.Icon></MenuItem>

code-behind:

 Private Sub OnClose(sender As Object, e As ExecutedRoutedEventArgs)
        Application.Current.Shutdown()
    End Sub

But the option ("Salir" in this case appears disabled... have not idea why!!


Primary platform is Windows 7 Ultimate 64 bit along with VS 2012/Sql2k8 for WPF and SilverLight stuff

WPF & OpenFileDialog (Win32 vs Forms)

$
0
0

I'm a programming student and I'm presently enrolled in a class teaching C# using WPF. All of my previous experience has been in WinForms and this has lead to some interesting issues. The most interesting issue I've had is that WPF apparently doesn't have it's own OpenFileDialog class we are apparently supposed to use either System.Windows.Forms or Microsoft.Win32. It seems both work for the purpose of creating an Open File window however there are differences in the classes.

Using the System.Windows.Forms.OpenFileDialog causes name conflicts with various System.Windows.Controls.

e.g) There are buttons defined in each.

Using Microsoft.Win32 removes the ability to use DialogResult and instead Nullable<bool> is used.

Effectively I just want to know which one I should be using and why there isn't simply one control in System.Windows.Controls that is utilized across UI Types (Since it's just a wrapper around native code from what I understand).

Thanks in advance.

A little bit of imagination (TextDecorations)

$
0
0

Hi there,

This is one image with one HyperLink in order to use ICommand interface (simulating a button):

<TextBlock DockPanel.Dock="Top"><Hyperlink Command="New"><Image Source="/Imagenes/new.png" Name="Nuevo_Registro" Opacity="0.3" Width="32" Margin="6"

ToolTip="{Resx LabelNuevoRegistro}" /></Hyperlink></TextBlock>

Using this style in order to drop off the below line:

<Style x:Key="{x:Type Hyperlink}" TargetType="Hyperlink"><Setter Property="TextDecorations"
           Value="{x:Null}" /></Style>

And..causing that my ToolTip doesn't appear..

ToolTip="{Resx LabelNuevoRegistro}"

suppose that VS consider ToolTip like just TextDecorations stuff...

Any ideas??


Primary platform is Windows 7 Ultimate 64 bit along with VS 2012/Sql2k8 for WPF and SilverLight stuff


Lack of headers

$
0
0

Hi All

I am having trouble with viewing .htm files, when they are in Split view, the header and left and bottom tool bars are visible in the source but not in design. When you click on the text in the source it highlights in the design but not at the same spot. I am currently evaluating Microsoft Visual Studio Express 2012 for Web- in administrator mode. Can I run this program in a user mode or will it only work in admin mode?

Thanks

WPF Frame can not inherit value from parent

$
0
0

Hello

 If the parent control defines a value for the property "Foreground". The WPF elements inside the Frame will not inherit that properties value.

If I add New Page to frame . then I change theme of window then it is not applying to page of the frame.

Why it is not inheriting from parent?

I need to make it null & again set theme on load of frame.

it cause performance slow of application.

Can you please help me for it?

Ref questions:

http://www.devexpress.com/Support/Center/Question/Details/Q459031

https://connect.microsoft.com/VisualStudio/feedback/details/520355/wpf-frame-control-stops-property-inheritanceI am not getting any proper solution for it.

can you please sugest me any solution for it?

Thanking you in advance..

Regards

Vipul Langalia


Change TextBlock Foreground color based on its Background color

$
0
0

In my WPF application, I have to keep on updating TextBlock background based on user conditions. TextBlock style is defined in App.xaml. If the background is too dark (Green/Blue) I want to set the foreground to white else black. How can I achieve this? I explored following two options:

  1. Via DataTriggers: In App.xaml:

This doesn't seem to work. I never see an update in textblock's foreground property. While debugging, I see the following for the binding: <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

System.Windows.Data Warning: 72 : RelativeSource.Self found TextBlock (hash=61003640) System.Windows.Data Warning: 78 : BindingExpression (hash=6398298): Activate with root item TextBlock (hash=61003640) System.Windows.Data Warning: 107 : BindingExpression (hash=6398298): At level 0 using cached accessor for TextBlock.Background: DependencyProperty(Background) System.Windows.Data Warning: 104 : BindingExpression (hash=6398298): Replace item at level 0 with TextBlock (hash=61003640), using accessor DependencyProperty(Background) System.Windows.Data Warning: 101 : BindingExpression (hash=6398298): GetValue at level 0 from TextBlock (hash=61003640) using DependencyProperty(Background): SolidColorBrush (hash=58614288) System.Windows.Data Warning: 80 : BindingExpression (hash=6398298): TransferValue - got raw value SolidColorBrush (hash=58614288) System.Windows.Data Warning: 89 : BindingExpression (hash=6398298): TransferValue - using final value SolidColorBrush (hash=58614288) <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

What is "SolidColorBrush (hash=58614288)"? Is it the Hex color code or hascode for the object of type SolidColorBrush?

  1. Using IValueConverter: Have not tried it since I don't want to convert one value to another but change a UIElement's property based on some other property change. Also, wouldn't converters will give a performance hit since almost all UIElements use TextBlock internally to display data?

Any help is highly appreciated.

Thanks,

RDV

Database value doesn't display in wpf combobox

$
0
0

I've messed something up but cannot figure out what.  I have a datagrid that used to display a value coming from the database just fine.  Then I changed the cell on the datagrid to a combobox.  The combo drops down with the correct items but now the combo does not display the value coming from the database.

Xaml:

<DataGridComboBoxColumn x:Name="cboDentistAppointmentTimes" Header="Appointment Time" TextBinding="{Binding DentistAppointmentTime}" />


Code to bind combo:

        Dim AppointmentTimes As New List(Of String)() From { _"8:00", _"9:00", _"10:30" _
        }

        cboDentistAppointmentTimes.ItemsSource = AppointmentTimes

When the datagrid is displayed, no values from the database are displayed.  The cell is blank.  How do I get that value back?

Thanks.


Kris Hood

Problem creating editable ListBox Item with an external button

$
0
0

I created a simple ListBoxItemStyle that contains a TextBox with its Visibility set to Collapsed and a trigger based on the ListBoxItem Tag property being set to True which sets the TextBox Visibility to Visible.   Then in the Click event for the button I set its Tag value to True.   But when I click the button and set the Tag Value to True nothing happens.  If I change the Trigger to be IsSelected instead of Tag the edit works each time I click on an item in the Listbox.  But I want to only have the edit active if I click the Button.

I don't know what I am doing wrong?

<Style x:Key="ListBoxItemStyle1" TargetType="{x:Type ListBoxItem}"><Setter Property="Background" Value="Transparent"/><Setter Property="HorizontalContentAlignment" Value="{Binding HorizontalContentAlignment, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"/><Setter Property="VerticalContentAlignment" Value="{Binding VerticalContentAlignment, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"/><Setter Property="Padding" Value="2,0,0,0"/><Setter Property="Template"><Setter.Value><ControlTemplate TargetType="{x:Type ListBoxItem}"><Grid><Border x:Name="Bd" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="true"><ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/></Border><TextBox x:Name="EditableText" LostFocus="RenameLostFocus"  Visibility="Collapsed"/></Grid><ControlTemplate.Triggers><Trigger Property="IsSelected" Value="true"><Setter Property="Background" TargetName="Bd" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/><Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}"/></Trigger><MultiTrigger><MultiTrigger.Conditions><Condition Property="IsSelected" Value="true"/><Condition Property="Selector.IsSelectionActive" Value="false"/></MultiTrigger.Conditions><Setter Property="Background" TargetName="Bd" Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"/><Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/></MultiTrigger><Trigger Property="IsEnabled" Value="false"><Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/></Trigger><Trigger Property="Tag" Value="true"><Setter TargetName="EditableText" Property="Visibility" Value="Visible" /><Setter TargetName="EditableText" Property="Text" Value="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Content}"/></Trigger></ControlTemplate.Triggers></ControlTemplate></Setter.Value></Setter></Style>

I then bind the Tag property of the ListBoxItem to the Button Tag Property

<ListBox ItemsSource="{StaticResource MyFiles}"  ItemContainerStyle="{DynamicResource ListBoxItemStyle1}"><ListBox.Resources><Style TargetType="{x:Type ListBoxItem}"><Setter Property="Tag" Value="{Binding Path=Tag,ElementName=bt_RENAME}"/></Style></ListBox.Resources></ListBox>


<Button x:Name="bt_RENAME" Content="RENAME" Click="bt_Rename" />

	Private Sub bt_Rename(sender as Object, e as RoutedEventArgs)sender.Tag = True
	End Sub


Jeff Davis

Animate the width property of a TextBlock

$
0
0

Hi to all,
I have a TextBlock inside a cell of a Grid which I want to animate every time the text changes. My idea is to animate the width property of the TextBlock starting from zero to ActualWidth. As a result, the cell will progressively expand giving a "growing effect".

XAML:

<Grid MouseEnter="Grid_MouseEnter" Background="Green" HorizontalAlignment="Left" Margin="27,23,0,0" VerticalAlignment="Top"><Grid.ColumnDefinitions><ColumnDefinition Width="20"/><ColumnDefinition Width="Auto"/></Grid.ColumnDefinitions><Grid.Triggers><EventTrigger RoutedEvent="MouseLeave"><EventTrigger.Actions><BeginStoryboard><Storyboard Storyboard.TargetName="MyTxt" Storyboard.TargetProperty="Width" ><DoubleAnimation To="0"
                                                 Duration="0:0:1" /></Storyboard></BeginStoryboard></EventTrigger.Actions></EventTrigger></Grid.Triggers><TextBlock TargetUpdated="MyTxt_TargetUpdated" Tag="{Binding ElementName=MyTxt, Path=ActualWidth, NotifyOnTargetUpdated=True}" Grid.Column="1" Width="0"  HorizontalAlignment="Left" Name="MyTxt" VerticalAlignment="Top"><TextBlock.Triggers><EventTrigger RoutedEvent="Binding.TargetUpdated"><EventTrigger.Actions><!--<BeginStoryboard><Storyboard Storyboard.TargetName="MyTxt" Storyboard.TargetProperty="Width" ><DoubleAnimation From="0"
                                        To="{Binding ElementName=MyTxt, Path=ActualWidth}"
                                        Duration="0:0:1"/></Storyboard></BeginStoryboard>--></EventTrigger.Actions></EventTrigger></TextBlock.Triggers></TextBlock></Grid>

Code behind:

	private void Grid_MouseEnter(object sender, MouseEventArgs e)
        {
            if (this.MyTxt.Text == "Short content")
                this.MyTxt.Text = "Looooooooooooong content";
            else
                this.MyTxt.Text = "Short content";
        }

        private void MyTxt_TargetUpdated(object sender, DataTransferEventArgs e)
        {
            var txtAnim = new DoubleAnimation();
            txtAnim.Duration = new Duration(TimeSpan.FromMilliseconds(1000));
            txtAnim.From = 0;
            txtAnim.To = this.MyTxt.ActualWidth;
            var sb = new Storyboard();
            sb.Children.Add(txtAnim);
            Storyboard.SetTargetProperty(txtAnim, new PropertyPath(TextBlock.WidthProperty));
            Storyboard.SetTarget(txtAnim, this.MyTxt);
            txtAnim.Freeze(); 
            sb.Begin();
        }

Unfortunately it doesn't work: during the first attempt, nothing happens. On the second attempt, the TextBlock animates, but using the ActualWidth of the first execution. On the third attempt, for unknown reasons, the animation enter in an infinite loop.
The animation works as expected if I create and start the Storyboard in code behind (inside the "MyTxt_TargetUpdated" event).
I don't know why this strange behaviour. The storyboard in xaml is the same of the one created in code behind. If it works in code behind, then, it should work also in xaml.

The code above is in "code behind" mode and shows how the animation should be.
To enable "xaml mode" just comment the code inside "MyTxt_TargetUpdated" and uncomment the BeginStoryboard section in the xaml side.

Any help would be appreciated.
Thanks

Dependency Properties and Attached Properties

$
0
0

hi,

i am not clear with the concepts behind Depencency properties and Attached properties after reading so many time with reference of books and internet.

can you please explain in terms of real time use of DP and AP  and not in bookish way.

with realtime example of 1 or 2 that may help in understanding.

Viewing all 18858 articles
Browse latest View live


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