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

How can I group a viewmodel by its first letter?

$
0
0

I wanna to make a stackpanel just like windows 10 startup menu.

All the program will group by its first letter.

Now I created a model:

public class Program{

   public string Name{get;set;}

   public string Path{get;set;}

}

I do not make the icon to make it easier.

And now how can I group all of this?

I think the most difficult is to create a header just like C as below in each group:

What's more, whenever the name of the program changes, it will changes the group if its first letter changes also.

How can I do this? Thank you.


IndexOf string from a list in a custom class

$
0
0

Need to compare a string against a collection and get the IndexOf so I can set the ComboBox to the current item.

I add the collection to Version Class and populate a ComboBox, but can't work out how to retrieve the items from the class.

This is my code behind with the attempt to retrieve the Index number.

Public Sub Init()
    Dim di As New IO.DirectoryInfo(pathtofolders)
    For Each subdi As IO.DirectoryInfo In di.GetDirectories
        Dim items As List(Of Versions) = New List(Of Versions)()
        cmbVersion.Items.Add(items)
        items.Add(New Versions() With {
            .ver = subdi.Name
        })
    Next

    If Not ver.IndexOf("12") = -1 Then
        Console.WriteLine(True)
    Else
        Console.WriteLine(False)
    End If

End Sub

Public Class Versions
    Public Property ver As String
End Class

Do you want to be acknowledged as the next WPF Guru? Submit your work to July 2019 competition!

$
0
0


What is TechNet Guru Competition?

Each month Microsoft TechNet Wiki council organizes a contest of the best articles posted that month. This is your chance to be announced as MICROSOFT TECHNOLOGY GURU OF THE MONTH!

One winner in each category will be selected each month for glory and adoration by the MSDN/TechNet Ninjas and community as a whole. Winners will be announced in dedicated blog post that will be published inMicrosoft Wiki Ninjas blog, a tweet fromMicrosoft Wiki Ninjas Twitter account, links will be published atMicrosoft TNWiki group on Facebook, and other acknowledgement from the community will follow.

Some of our biggest community voices and many MVPs have passed through these halls on their way to fame and fortune.

If you have already made a contribution in the forums or gallery or you published a nice blog, then you can simply convert it into a shared wiki article, reference the original post, and register the article for the TechNet Guru Competition. The articles must be written in July 2019 and must be in English. However, the original blog or forum content can be from beforeJuly 2019.

Come and see who is making waves in all your favorite technologies. Maybe it will be you!


Who can join the Competition?

Anyone who has basic knowledge and the desire to share the knowledge is welcome. Articles can appeal to beginners or discusse advanced topics. All you have to do is to add your article to TechNet Wiki from your own specialty category.


How can you win?

  1. Please copy/Write over your Microsoft technical solutions and revelations to TechNetWiki.
  2. Add a link to your new article on THIS WIKI COMPETITION PAGE (so we know you've contributed)
  3. (Optional but Recommended) Add a link to your article at the TechNetWiki group on Facebook to get feedback and tips from the council members and from the community. The group is very active and people love to help. You can even get direct improvements to your article before the contest starts.

Do you have any question or want more information?

Feel free to ask any questions below, or Join us at the official MicrosoftTechNet Wiki groups on facebook. Read More about TechNet Guru Awards.

If you win, people will sing your praises online and your name will be raised as Guru of the Month.

PS: Above top banner came from James van den Berg.


Please, If you think your question has been answered click "Mark as Answer" if just helped click "Vote as helpful". This can be beneficial to other community members reading this forum thread.

Scale on condition

$
0
0

Hi,

I have this structure in place for now:

<ItemsControl.ItemsPanel><ItemsPanelTemplate><WrapPanel MaxWidth="500"
                           Height="85"
                           ClipToBounds="False" /></ItemsPanelTemplate></ItemsControl.ItemsPanel><ItemsControl.ItemTemplate><DataTemplate><Canvas  Width="95"
                         Height="70"><StackPanel Orientation="Vertical"                                                                                                
                                ClipToBounds="False"
                                RenderOptions.BitmapScalingMode="NearestNeighbor"
                                RenderTransformOrigin="0.5,0.5"
                                Width="95"><StackPanel.RenderTransform><ScaleTransform /></StackPanel.RenderTransform><StackPanel.Triggers><EventTrigger RoutedEvent="Mouse.MouseEnter"><EventTrigger.Actions><BeginStoryboard Name="ExpandText"><Storyboard><DoubleAnimation
                                                    Storyboard.TargetProperty="RenderTransform.ScaleX"
                                                             To="1.3"
                                                             Duration="0:0:0.2" /><DoubleAnimation
                                                    Storyboard.TargetProperty="RenderTransform.ScaleY"
                                                             To="1.3"
                                                             Duration="0:0:0.2" /></Storyboard></BeginStoryboard></EventTrigger.Actions></EventTrigger><EventTrigger RoutedEvent="Mouse.MouseLeave"><EventTrigger.Actions><BeginStoryboard Name="NormalText"><Storyboard><DoubleAnimation
                                                    Storyboard.TargetProperty="RenderTransform.ScaleX"
                                                             To="1"
                                                             Duration="0:0:0.2" /><DoubleAnimation
                                                    Storyboard.TargetProperty="RenderTransform.ScaleY"
                                                             To="1"
                                                             Duration="0:0:0.2" /></Storyboard></BeginStoryboard></EventTrigger.Actions></EventTrigger></StackPanel.Triggers><Border Name="MyBorder"
                                Margin="10,10,10,10"
                                Height="35"
                                ClipToBounds="False"
                                Width="75"                                                                                                
                                CornerRadius="5">                                                                                               ><Grid HorizontalAlignment="Stretch"
                                  ClipToBounds="False"
                                  VerticalAlignment="Stretch"><Button HorizontalAlignment="Stretch"
                                                    Height="30"
                                                    Margin="3"                                                                                                                   
                                                    IsEnabled="True"
                                                    Focusable="False"                                                                                                                    /><TextBlock FontSize="20"
                                           FontFamily="Verdana"
                                           Margin="0"                                                                                                           
                                           HorizontalAlignment="Center"
                                           VerticalAlignment="Center"
                                           TextTrimming="CharacterEllipsis"                                                                                                           
                                           IsHitTestVisible="False" /></Grid></Border><TextBlock TextTrimming="CharacterEllipsis"
                                   HorizontalAlignment="Center"/></StackPanel></Canvas></DataTemplate></ItemsControl.ItemTemplate>

Right now the buttons scale when I move the mouse on them but

What I want:

1. When I shrink the window the items in the wrap panel should first start wrapping.

2. Once they reach a certain size, they should start shrinking due to the view box.

3. Scaling on mouse over should work only when they shrink to a certain size.

Can anyone help me out.

Thank you.


Please Mark as Answered if this answers your question Or UnMark as Answered if it did not. Happy to Help :)

Best Practice - Binding a Custom User Control in a ListBox

$
0
0

I have a .Net C# WPF MVVM application I'm working on and need to bind a Collection to a custom User Control (ReviewLetterItem) and list in a ListBox. I can get the custom control to display properly but unclear on the best way to bind the data.

My original approach was to build an ObservabaleCollection of the custom user control and bind to the itemsource of the ListBox. In building the collection, a property on the ViewModel for the ReviewLetterItem is being populated for each instance in the Collection. It's not displaying any of the data so I'm unsure of the best practice.

               <ListBox 
                    Name="ReviewSendListbox" 
                    ItemsSource="{Binding ReviewSendList, Mode=TwoWay }" 
                    Grid.Column="0" Grid.Row="1" 
                    Height="Auto" Width="Auto" MinHeight="300" Margin="0,0,0,0"
                    HorizontalAlignment="Left"  VerticalAlignment="Top" 
                    SelectionMode="Single">
                    <ListBox.ItemTemplate >
                        <DataTemplate>
                            <items:ReviewLetterItem Content="{Binding}"/>
                        </DataTemplate> 
                    </ListBox.ItemTemplate>
                </ListBox>
 


chuck

How do I get the last item from collection

$
0
0

I would like to select the last item from a list but don't know enough about how it works to do it.

The last value will be used in a string further down the code.

Error is 'Conversion from string "10" to type 'Boolean' is not valid.'

Public Sub Init() Dim di As New IO.DirectoryInfo(pathtofolders) Dim items As List(Of Versions) = New List(Of Versions)() For Each subdi As IO.DirectoryInfo In di.GetDirectories items.Add(New Versions() With { .ver = subdi.Name }) Next cmbVersion.ItemsSource = items

Dim index = items.Last(Function(v) v.ver) 'Error here End Sub Public Class Versions Public Property ver As String End Class



Customized WPF Window with WindowChrome

$
0
0

Hi

I have a WPF Customized Window, with below settings,

 WindowStyle="SingleBorderWindow"  

<WindowChrome.WindowChrome>
        <WindowChrome CaptionHeight="0" NonClientFrameEdges="None" ResizeBorderThickness="5" GlassFrameThickness="0"/>
    </WindowChrome.WindowChrome>

Problem Statement: While maximizing the Window, a black strip (20 pixels height) is displayed for a while, at the Top Left position.

How to resolve the above stated behavior?

Thanks in advance,

Vijay Zalaki

Create DataGrid: All Headers, Cells and Contents Align to Center All & Width and Height Bind to Vectorel * in WPF C#

$
0
0

I have a observable collection which include many class content. If I set the datagrid itemsource as the observablecollection, datagrid is created well without any problems.

My problem is alignment all cells and headers as horizontal and vertical. And also must be created auto column and width must be equal content width.

I try to dynamicresources but not succeed entirely.

<Style x:Key="MyAim" TargetType="{x:Type DataGrid}"><Setter Property="Height" Value="Auto"/><Setter Property="Width" Value="Auto"/><Setter Property="AlternatingRowBackground" Value="White"/><Setter Property="RowBackground" Value="White"/><Setter Property="Background" Value="White"/><Setter Property="CanUserReorderColumns" Value="False"/><Setter Property="CanUserSortColumns" Value="False"/><Setter Property="CanUserResizeRows" Value="False"/><Setter Property="CanUserResizeColumns" Value="False"/><Setter Property="CanUserAddRows" Value="False"/><Setter Property="CanUserDeleteRows" Value="False"/><Setter Property="VerticalAlignment" Value="Center"/><Setter Property="HorizontalAlignment" Value="Center"/><Setter Property="VerticalContentAlignment" Value="Center"/><Setter Property="HorizontalContentAlignment" Value="Center"/><Setter Property="HeadersVisibility" Value="Column"/><Setter Property="GridLinesVisibility" Value="All" /><Setter Property="HorizontalScrollBarVisibility" Value="Hidden" /><Setter Property="VerticalScrollBarVisibility" Value="Visible" /><Setter Property="ColumnWidth" Value="Auto"/><Setter Property="AutoGenerateColumns" Value="True"/></Style>

Need to datagrid viewing like that:


Send Data To WebBrowser and Json Serialize List For WebBrowser In WPF C#

$
0
0

I want to achieve like this cycle:

  • Save many datas in List<>
  • Send List<> to WebBrowser Html
  • Convert List<> Json Serialize
  • Use List elements in JavaScript (ChartJs)

I have achieved this cycle in Asp.Net Core. I was sending data @Model in Html and render chart perfectly. Here is example:

<html><head>
    @section Scripts{<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.min.js"></script><script src="https://code.jquery.com/jquery-3.3.1.min.js"></script><script>
    var ctx = document.getElementById('myChart').getContext('2d');
    var model = @Html.Raw(Json.Serialize(Model));
    //If Model is a List<>, model is an array, you need to loop it to get data
    var xAxis = [];
    var yAxis = [];

    $.each(model.data_Axis_X, function (index, item) {
        xAxis.push(item.toString());
    });
    $.each(model.data_Axis_Y, function (index, item) {
        yAxis.push(item.toString());
    });

    var myChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: xAxis,
            datasets: [{
                label: '# of Votes',
                data: yAxis,
                borderColor: [
                    'rgba(255, 99, 132, 1)',
                    'rgba(54, 162, 235, 1)',
                    'rgba(255, 206, 86, 1)',
                    'rgba(75, 192, 192, 1)',
                    'rgba(153, 102, 255, 1)',
                    'rgba(255, 159, 64, 1)'
                ],
                borderWidth: 1
            }]
        },
        options: {
            scales: {
                yAxes: [{
                    ticks: {
                        beginAtZero: true
                    }
                }]
            }
        }
    });
        </script>
    }</head><body><div><canvas id="myChart" width="400" height="400"></canvas></div></body></html>

Now, I want to achieve in WPF C# because I want to use ChartJS Please help me.

Video to Image sequence with separated audio c# wpf

$
0
0
I have video with audio (.avi, .mp4) and I want to make an image sequence with separated audio from it. I want to display this sequence in canvas (1 picure at the time) and to make the audio "could be played" = if user wants, he/ she can play it, othervise it will not be played. Is it possible? Thanks.

XamlSetTypeConverter attribute does not seem to work

$
0
0

I have MyButton class that extends Button. Inside MyButton, there is a bool property named "BooleanValue". I have set XamlSetTypeConverter attribute on MyButton. But when I set value of BooleanValue from xaml, the ReceiveTypeConverter static method in MyButton doesn't seem to be invoked at all. Based on my understandings, xaml uses BooleanConverter to convert string values to boolean values. Hence, the ReceiveTypeConverter method has to be called. What is the problem?

MyButton class:

    [XamlSetTypeConverter("ReceiveTypeConverter")]
    public class MyButton : Button
    {
        public bool BooleanValue { get; set; }

        public static void ReceiveTypeConverter(object targetObject, XamlSetTypeConverterEventArgs args)
        {
        }

    }

Usage:

<local:MyButton BooleanValue="False" />




ZIndex doesn't work!

$
0
0

In my application when the mouse is over certain controls they scale and become big.

Problem is as they expand, parts of it are covered by other controls. So I set ZIndex of the current control to 9999, but that doesn't work. 

How to get the current control (the one which has mouse over) to be the top most control in the whole application?


Please Mark as Answered if this answers your question Or UnMark as Answered if it did not. Happy to Help :)

how can i get setup .exe from my application?

$
0
0

Hi everybody!

This is my very first post here and I am a little hesitant about the question. I have been coding for about a year and so far I have been able to google my way out of troubles. This question has been asked before for sure but for some reason the answers I have found have not helped me.

I finished writing a WPF desktop application in C# which uses a SQL service-based database. The app writes to and reads from the database. The whole thing has a little over 5,000 lines of C# code.  It works perfectly in my machine. The problem comes when I try to publish the application. The deployment goes smoothly (apparently) but the application will NOT run in other machines. Actually, the first window opens, this is the login window. After loging in, when the next window should open,the app throws an exception. I am catching this exception in the "try-catch" block that sorrounds the code to connect to the SQL database so the error message I get is one that I wrote. I think (in my limited understanding) the problem is that the SQL database connection string is hardcoded into the app and that causes problems for the app to run when it finds itself in different machine. It canot find the database where the connection string says it is!!! Am I not understanding something? Is my problem something else? How do I fix this?

UWP Audio graph takes longer time to initialize when called from toast click handler

$
0
0

Hi All,

Ref https://stackoverflow.com/questions/56928082/uwp-audio-graph-takes-longer-time-to-initialize-when-called-from-toast-click-han

I am giving user an option to enable AudioGraph once he clicked on toast button. I am using the OnActivated method to receive the toast button click handler.

code goes as give below

protectedoverride async voidOnActivated(IActivatedEventArgs args){//CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, () => {//   var result = GetAutio().GetAwaiter().GetResult();//});if(args isToastNotificationActivatedEventArgs){var result = await Windows.Media.Audio.AudioGraph.CreateAsync(newAudioGraphSettings(AudioRenderCategory.Speech){EncodingProperties=Windows.Media.MediaProperties.AudioEncodingProperties.CreatePcm(FREQUENCY, CHANNELS, BITS),});}}

Problem with above code is that CreateAsync takes a long time to return, whereas if i call the same code from button click then it takes less than a sec to return.

Button click handler

private async voidButton_Click(object sender,RoutedEventArgs e){//System.Threading.Thread t = new System.Threading.Thread(() => {var result = await Windows.Media.Audio.AudioGraph.CreateAsync(newAudioGraphSettings(AudioRenderCategory.Speech){EncodingProperties=Windows.Media.MediaProperties.AudioEncodingProperties.CreatePcm(FREQUENCY, CHANNELS, BITS),});//var result1 = result.AsTask<CreateAudioGraphResult>().GetAwaiter().GetResult();//result1.Graph.Stop();//GetAutio().ConfigureAwait(false).GetAwaiter().GetResult();}

As the commented code show I have also try to run the toast button click handler with UI thread still it takes longer timer to initialize.

Any idea why this is happening?

Regards, Pavan Tiwari

How can I binding a dbset to ItemsControl?

$
0
0

I wanna connect to a Sqlite database with EF Core and followed this tutorial(https://docs.microsoft.com/en-us/ef/core/get-started/netcore/new-db-sqlite).

All works well(including insert/delete/update and so on).

There is a DbContext:Database.ProductDbContext PDC = new Database.ProductDbContext();

And also I want to bind the dbset PDC.StoreIn to a ItemsControl.

I tried bind it like this but it did not work at all:

<ItemsControl ItemsSource="{Binding PDC+StoreIn">
</ItemsControl>

However, if I convert it to a ObservableCollection and bind it, it works. Just like this:

public ObservableCollection OC = new ObservableCollection<Database.StoreIn>(PDC.StoreIn);

<ItemsControl ItemsSource="{Binding OC">
</ItemsControl>

Whereas, as we know, whenever the database insert/update/delete, the ObservableCollection will not update so I have to bind the database directly.

How can I bind the dbset? Thank you.


WPF Window shows Vertical Stripes while changing state

$
0
0

Hi

I have a WPF Customized Window, with below settings,

 WindowStyle="SingleBorderWindow"  

<WindowChrome.WindowChrome>
        <WindowChrome CaptionHeight="0" ResizeBorderThickness="5" GlassFrameThickness="0"/>
    </WindowChrome.WindowChrome>

NonClientFrameEdges is binded to Window Name.

Problem Statement: With "Animate Windows when minimizing and maximizing" option is unchecked, While maximizing the Window, vertical stripes are displayed.

How to resolve the issue so that displaying vertical stripes can be avoided while maximizing the window.

Thanks in advance.

ExecutionEngineException on certain IME input of TextBox

$
0
0

I have my laguage for non unicode programs set to Japanese (Windows XP) and if I type certain data into a WPF TextBox while the IME is on, I get the following exception:

 

System.ExecutionEngineException was unhandled
  Message="Exception of type 'System.ExecutionEngineException' was thrown."

FatalExecutionEngineError was detected
Message: The runtime has encountered a fatal error. The address of the error was at 0x5688b6db, on thread 0xa2bc. The error code is 0x80131623. This error may be a bug in the CLR or in the unsafe or non-verifiable portions of user code. Common sources of this bug include user marshaling errors for COM-interop or PInvoke, which may corrupt the stack.

This is repeatable.  I just type "Th" (capital T so IME uses single spaced characters) then delete the "h" so your left with "T" then press the "space bar".

 

Basically if you delete a character and then press space while the IME has the text your typing still underlined, it will throw that error.

 

 

I have Visual Studio 2008 Beta 2 Installed (and thus .NET 3.5).

Printing without Preview in Windows 10 UWP app

$
0
0


How to achieve silent printing in windows 10 UWP app. Is there any solution to print documents without using print preview dialog in UWP.  


Maintain three values in collection like Collection

$
0
0
I am developing a WPF application in MVVM architecture. So I have many ViewModels and views in my project. For easy page navigation purpose, created a custom navigation services class and by passing viewmodel or view name I need to get other.
below method will call at starup.

private static void ConfigureNavigation()
{
	Uri test = new Uri("../Views/LoginView.xaml", UriKind.Relative); // I don't know how to pass to dictonary.
	NavigationService.Register<LoginViewModel, LoginView>();
	NavigationService.Register<MaintainerViewModel, MaintainerView>();
}

below code is the register method of navigation service

private static readonly ConcurrentDictionary<Type, Type> ViewModelMap = new ConcurrentDictionary<Type, Type>();
public static void Register<TViewModel, TView>() where TView : Page
{
	if (!ViewModelMap.TryAdd(typeof(TViewModel), typeof(TView)))
	{
		throw new InvalidOperationException($"ViewModel already registered '{typeof(TViewModel).FullName}'");
	}
}

Requirement 1
I need to navigate the frame to specified url using viewmodel..

Frame.Navigate(GetView(viewModelType), UriKind.Relative);

public static Uri GetView(Type viewModel)
{
	if (ViewModelMap.TryGetValue(viewModel, out Type view))
	{
		return;  Here I need to return url, which is registered in the register method;
	}
	throw new InvalidOperationException($"View not registered for ViewModel '{viewModel.FullName}'");
}

By passing viewmodel I need to get view and url..

Requirement 2
I need to get the viewmodel by using view name..

public static Type GetViewModel(Type view)
{
	var type = ViewModelMap.Where(r => r.Value == view).Select(r => r.Key).FirstOrDefault();
	if (type == null)
	{
		throw new InvalidOperationException($"View not registered for ViewModel '{view.FullName}'");
	}
	return type;
}

By passing view I need to get view.
By passing view I need to get viewmodel.

how to pass Uri from the ConfigureNavigation() to navigation service and don't know how to get from dictionary. The only problem is passing Uri.

any help..
How to pass uri to Register() method and get in GetView() method


Disable GoForward/GoBackward CHtmlView

$
0
0

Hi,

I'm using a CHTMLView component in my c++ application, and I want to prevent the user from navigating back or forward. Is there a way to do that? I tried setting the "Navigate2" options "navNoHistory | navOpenInNewTap | navNoReadFromCache | navNoWriteToCache" but that didn't work. 

Viewing all 18858 articles
Browse latest View live


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