xaml codes are here;
<Window x:Class="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">
<Grid>
<TextBlock x:Name="TextBlock1" Width="100" Height="20" Background="Blue"/>
</Grid>
</Window>
vb.net codes are here;
Class MainWindow
Private Sub MainWindow_Loaded(sender As Object, e As RoutedEventArgs) Handles Me.Loaded
Dim myBrush1 As New SolidColorBrush(CType(ColorConverter.ConvertFromString("#FF0000"), Color))
TextBlock1.Background = myBrush1
End Sub
End Class
The codes above are okey.
My question is here;
I want to use
TextBlock1.Background = "myBrush" & 1
instead of
TextBlock1.Background = myBrush1
TextBlock1.Background = "myBrush" & 1 is not working.
So, how can I make TextBlock1.Background = "myBrush" & 1 is working?
You can't use a string as a variable name in that way.
What you can do instead is have some kind of collection which associates an object (in this case a Brush) with a string. A Dictionary will serve this purpose well here.
You could have something like:
Class MainWindow
Private myBrushes As New Dictionary(Of String, Brush)
Private Sub Window_Loaded(sender As Object, e As RoutedEventArgs)
Dim myBrush1 As New SolidColorBrush(DirectCast(ColorConverter.ConvertFromString("#FF0000"), Color))
myBrushes.Add("myBrush1", myBrush1)
TextBlock1.Background = myBrushes("myBrush" & "1")
End Sub
End Class
The value of myBrushes("myBrush1") is the SolidColorBrush myBrush1. You can add as many brushes as you want to the dictionary.
Related
Following code is okey in vb.net and Windows Form Application.
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim comboSource As New Dictionary(Of String, String)()
comboSource.Add("1", "Sunday")
comboSource.Add("2", "Monday")
comboSource.Add("3", "Tuesday")
comboSource.Add("4", "Wednesday")
comboSource.Add("5", "Thursday")
comboSource.Add("6", "Friday")
comboSource.Add("7", "Saturday")
ComboBox1.DataSource = New BindingSource(comboSource, Nothing)
ComboBox1.DisplayMember = "Value"
ComboBox1.ValueMember = "Key"
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim key As String = DirectCast(ComboBox1.SelectedItem, KeyValuePair(Of String, String)).Key
Dim value As String = DirectCast(ComboBox1.SelectedItem, KeyValuePair(Of String, String)).Value
MessageBox.Show(key & " " & value)
End Sub
End Class
I want to convert above codes to WPF Application.
xaml
<Window x:Class="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">
<Grid>
<ComboBox x:Name="ComboBox1" Height="20" Width="150"/>
<Button x:Name="Button1" Height="20" Width="80" VerticalAlignment="Top" Content="Click Me"/>
</Grid>
</Window>
vb.net
Class MainWindow
Private Sub MainWindow_Loaded(sender As Object, e As RoutedEventArgs) Handles Me.Loaded
Dim comboSource As New Dictionary(Of String, String)()
comboSource.Add("1", "Sunday")
comboSource.Add("2", "Monday")
comboSource.Add("3", "Tuesday")
comboSource.Add("4", "Wednesday")
comboSource.Add("5", "Thursday")
comboSource.Add("6", "Friday")
comboSource.Add("7", "Saturday")
ComboBox1.DataSource = New BindingSource(comboSource, Nothing)
ComboBox1.DisplayMember = "Value"
ComboBox1.ValueMember = "Key"
End Sub
Private Sub Button1_Click(sender As Object, e As RoutedEventArgs) Handles Button1.Click
Dim key As String = DirectCast(ComboBox1.SelectedItem, KeyValuePair(Of String, String)).Key
Dim value As String = DirectCast(ComboBox1.SelectedItem, KeyValuePair(Of String, String)).Value
MessageBox.Show(key & " " & value)
End Sub
End Class
Linked picture shows the errors: https://prnt.sc/kcig7j
So, how can I solve that errors?
The WPF equivalents for the WinForms properties are as follows:
DataSource -> ItemsSource
DisplayMember -> DisplayMemberPath
ValueMember -> SelectedValuePath
Also, bear in mind that you can set properties in either code-behind or in XAML, so your ComboBox definition could look like this:
<ComboBox x:Name="ComboBox1" Height="20" Width="150" DisplayMemberPath="Value" SelectedValuePath="Key" />
I personally would find it easier to set the ItemsSource property in code-behind:
Dim comboSource As New Dictionary(Of String, String)()
comboSource.Add("1", "Sunday")
comboSource.Add("2", "Monday")
comboSource.Add("3", "Tuesday")
comboSource.Add("4", "Wednesday")
comboSource.Add("5", "Thursday")
comboSource.Add("6", "Friday")
comboSource.Add("7", "Saturday")
ComboBox1.ItemsSource = comboSource
W.R.T. your event handler, you have a double cast to KeyValuePair(Of String, String); you should probably cast only once and store the casted value in a variable. But in this particular case, you don't have to even cast the SelectedItem. Instead, you can cast the sender to a ComboBox and read the Text and Value properties:
Dim cmb As ComboBox = sender
MessageBox.Show($"Key: {cmb.SelectedValue}, Value: {cmb.Text}')
Also note that you can just as easily use an Integer for your dictionary key as a String:
Dim days = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
Dim comboSource = days
.Select(Function(x, index) (item:=x, index:=index+1))
.ToDictionary(Function(x) x.index, Function(x) x.item)
I am trying to build a progressbar using MVVM. Basically, I have a main xaml and 2 UserControls, 1 for progressbar 1 for datagrid.
I am bit new and I followed this question and answer but I havent got any success. Below is my ViewModel code and Xaml code. Basically I have 2 problems,
1-How to bind CustomerModels or if even possible CustomerViewModel? I tried to use Itemsource binding direcly with ObservableCollection which I am filling with my delegateCommand that runs with a backgroundworker but no success. I tried without delegate and backgroundworker,simply using as below.
Me.myLoadCommand = New Commands.LoadCustomerModels()
What am I doing wrong?
<UserControl.Resources>
<vm:CustomerModelsVM x:Key="Customerobj"></vm:CustomerModelsVM>
</UserControl.Resources>
<Grid >
<DataGrid x:Name="grdData" ItemsSource="{Binding Path=CustomerModels}"/>
</Grid>
2-How to bind CurrentProgressBar? I tried to bind the progress bar status same way but I believe my ViewModel and Xaml somehow has no connection.
<UserControl x:Class="ucProgressBar"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
>
<Grid>
<ProgressBar Value="{Binding CurrentProgress, Mode=OneWay}" Visibility="{Binding ProgressVisibility}"></ProgressBar>
<TextBlock Text="{Binding ElementName=myProgressBar, Path=Value, StringFormat={}{0:0}%}" HorizontalAlignment="Center" VerticalAlignment="Center" />
</Grid>
Namespace ViewModels
Public Class CustomerModelsVM
Implements ICustomerModelsVM
Implements INotifyPropertyChanged
Public Event PropertyChanged As PropertyChangedEventHandler _
Implements INotifyPropertyChanged.PropertyChanged
Private ReadOnly worker As BackgroundWorker
Private m_currentProgress As Integer
Private _CustomerModels As New ObservableCollection(Of Models.CustomerModel)
Private mySaveCommand As ICommand
Private myLoadCommand As ICommand
Public Sub New()
Me.worker = New BackgroundWorker()
Me.myLoadCommand = New DelegateCommand(Sub() Me.worker.RunWorkerAsync(), AddressOf Progressisbusy)
' _CustomerModels = getCustomerModels()
Me.worker = New BackgroundWorker()
AddHandler Me.worker.DoWork, AddressOf Me.DoWork
AddHandler Me.worker.ProgressChanged, AddressOf Me.ProgressChanged
End Sub
Private Sub ProgressChanged(sender As Object, e As ProgressChangedEventArgs)
Me.CurrentProgress = e.ProgressPercentage
End Sub
Private Function Progressisbusy() As Boolean
Return Not Me.worker.IsBusy
End Function
Private Sub OnPropertyChanged(Optional ByVal propertyName As String = Nothing)
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
End Sub
Public ReadOnly Property CustomerModels() As ObservableCollection(Of Models.CustomerModel)
Get
Return _CustomerModels
End Get
End Property
Public ReadOnly Property btnClick() As ICommand
Get
Return myLoadCommand
End Get
End Property
Public Property CurrentProgress() As Integer
Get
Return Me.m_currentProgress
End Get
Private Set(value As Integer)
If Me.m_currentProgress <> value Then
Me.m_currentProgress = value
OnPropertyChanged(Me.CurrentProgress)
End If
End Set
End Property
Private Sub DoWork(sender As Object, e As DoWorkEventArgs)
_CustomerModels = getCustomerModels()
End Sub
Function getCustomerModels() As ObservableCollection(Of Models.CustomerModel) Implements ICustomerModelsVM.GetCustomerModels
If _CustomerModels Is Nothing OrElse _CustomerModels.Count = 0 Then myLoadCommand.Execute(_CustomerModels)
Return _CustomerModels
End Function
You can add the viewmodel as DataContext of the main window which is holding the two user controls. Please refer the below code.
<UserControl x:Class="UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<DataGrid x:Name="grdData" Height="200" ItemsSource="{Binding Path=CustomerModels}"/>
</Grid>
</UserControl>
<UserControl x:Class="UserControl2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" >
<StackPanel>
<Button Command="{Binding LoadCommand}">Test</Button>
<ProgressBar Value="{Binding CurrentProgress, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" Height="20" Width="200"
Visibility="{Binding ProgressVisibility}"></ProgressBar>
</StackPanel>
</UserControl>
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:StakOveflw"
Title="MainWindow" Height="350" Width="525">
<Grid>
<StackPanel>
<local:UserControl1/>
<local:UserControl2/>
</StackPanel>
</Grid>
</Window>
Class MainWindow
Public Sub New()
InitializeComponent()
Me.DataContext = New CustomerModelsVM()
End Sub
End Class
Imports System.ComponentModel
Imports System.Collections.ObjectModel
Imports Microsoft.Practices.Prism.Commands
Imports System.Threading
Public Class CustomerModelsVM
Implements INotifyPropertyChanged
Public Event PropertyChanged As PropertyChangedEventHandler _
Implements INotifyPropertyChanged.PropertyChanged
Private ReadOnly worker As BackgroundWorker
Private m_currentProgress As Integer
Private mySaveCommand As ICommand
Private myLoadCommand As ICommand
Public Property LoadCommand() As ICommand
Get
Return myLoadCommand
End Get
Set(ByVal value As ICommand)
myLoadCommand = value
End Set
End Property
Public Sub New()
Me.worker = New BackgroundWorker()
_CustomerModels = New ObservableCollection(Of CustomerModel)()
AddHandler Me.worker.DoWork, AddressOf Me.DoWork
AddHandler Me.worker.ProgressChanged, AddressOf Me.ProgressChanged
Me.worker.WorkerReportsProgress = True
myLoadCommand = New DelegateCommand(AddressOf LoadClick)
' _CustomerModels = getCustomerModels()
End Sub
Private Sub LoadClick()
Me.worker.RunWorkerAsync()
End Sub
Private Sub ProgressChanged(sender As Object, e As ProgressChangedEventArgs)
CurrentProgress = e.ProgressPercentage
End Sub
Private Function Progressisbusy() As Boolean
Return Not Me.worker.IsBusy
End Function
Private Function CalculateProgress(total As Integer, complete As Integer) As Integer
' avoid divide by zero error
If total = 0 Then
Return 0
End If
' calculate percentage complete
Dim result = CDbl(complete) / CDbl(total)
Dim percentage = result * 100.0
' make sure result is within bounds and return as integer;
Return Math.Max(0, Math.Min(100, CInt(Math.Truncate(percentage))))
End Function
Private Sub OnPropertyChanged(Optional ByVal propertyName As String = Nothing)
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
End Sub
Private _CustomerModels As ObservableCollection(Of CustomerModel)
Public Property CustomerModels() As ObservableCollection(Of CustomerModel)
Get
Return _CustomerModels
End Get
Set(ByVal value As ObservableCollection(Of CustomerModel))
_CustomerModels = value
End Set
End Property
Public Sub GetCustomers()
Dim total As Integer
total = 10000
For index = 1 To total
Dim a As CustomerModel = New CustomerModel()
a.NewProperty = "test" + index.ToString()
Application.Current.Dispatcher.Invoke(Windows.Threading.DispatcherPriority.Background, Function()
_CustomerModels.Add(a)
End Function)
worker.ReportProgress(CalculateProgress(total, index))
Next
End Sub
Public ReadOnly Property btnClick() As ICommand
Get
Return myLoadCommand
End Get
End Property
Public Property CurrentProgress() As Integer
Get
Return Me.m_currentProgress
End Get
Private Set(value As Integer)
Me.m_currentProgress = value
OnPropertyChanged("CurrentProgress")
End Set
End Property
Private Sub DoWork(sender As Object, e As DoWorkEventArgs)
_CustomerModels = getCustomerModels()
End Sub
Function getCustomerModels() As ObservableCollection(Of CustomerModel)
GetCustomers()
'Application.Current.Dispatcher.BeginInvoke(Windows.Threading.DispatcherPriority.Normal, New Action(Of Integer)(AddressOf GetCustomers), 3)
Return _CustomerModels
End Function
End Class
Public Class CustomerModel
Private newPropertyValue As String
Public Property NewProperty() As String
Get
Return newPropertyValue
End Get
Set(ByVal value As String)
newPropertyValue = value
End Set
End Property
End Class
I would like answer my question with a working solution. In my case problem was simply, I had to use dispatcher to clear my oberservable collection. So my Do_work function looks like as following. I didnt clear the observable collection before I start binding. Adding this simple line makes my code working.
Private Sub DoWork(sender As Object, e As DoWorkEventArgs)
Application.Current.Dispatcher.BeginInvoke(Sub() Me.CustomerModels.Clear())
' Me.CustomerModels.Clear()
For index = 1 To 100
Dim CustomerModel As New CustomerModel With { _
.age = 30 + index, _
.name = "testName" & index, _
.surname = "testSurname" & index, _
.Id = index}
Application.Current.Dispatcher.BeginInvoke(Sub() CustomerModels.Add(CustomerModel))
' CustomerModels.Add(CustomerModel)
Thread.Sleep(100)
worker.ReportProgress(CalculateProgress(100, index))
Next
End Sub
I am creating my own NumericUpDown control in VB. Here is my XAML:
<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
x:Class="NumericUpDown"
mc:Ignorable="d"
d:DesignHeight="30" d:DesignWidth="100">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="20" />
<ColumnDefinition Width="20" />
</Grid.ColumnDefinitions>
<TextBox x:Name="txtNum" Grid.Column="0" x:FieldModifier="private" TextChanged="txtNum_TextChanged"/>
<Button x:Name="cmdDown" Grid.Column="1" x:FieldModifier="private" Content="˅" Width="20" Click="cmdDown_Click" />
<Button x:Name="cmdUp" Grid.Column="2" x:FieldModifier="private" Content="˄" Width="20" Click="cmdUp_Click" />
</Grid>
</UserControl>
And here is the VB code behind it:
Class NumericUpDown
Dim _Minimum As Double = 0
Dim _Maximum As Double = 100
Private Sub NumericUpDown()
InitializeComponent()
txtNum.Text = Numeric
End Sub
Public Property Maximum As Double
Get
Return _Maximum
End Get
Set(value As Double)
_Maximum = value
End Set
End Property
Public Property Minimum As Double
Get
Return _Minimum
End Get
Set(value As Double)
_Minimum = value
End Set
End Property
Public Shared ReadOnly NumericProperty As DependencyProperty = DependencyProperty.Register("Numeric", GetType(String), GetType(NumericUpDown), _
New PropertyMetadata(""))
Public Property Numeric As String
Get
Return CType(GetValue(NumericProperty), String)
End Get
Set(value As String)
SetValue(NumericProperty, value)
End Set
End Property
Private Sub cmdUp_Click(sender As Object, e As RoutedEventArgs)
Dim NumValue As Double
NumValue = Val(txtNum.Text)
NumValue += 1
If NumValue > Maximum Then NumValue = Maximum
txtNum.Text = NumValue.ToString
End Sub
Private Sub cmdDown_Click(sender As Object, e As RoutedEventArgs)
Dim NumValue As Double
NumValue = Val(txtNum.Text)
NumValue -= 1
If NumValue < Minimum Then NumValue = Minimum
txtNum.Text = NumValue.ToString
End Sub
Private Sub txtNum_TextChanged(sender As Object, e As TextChangedEventArgs)
Numeric = txtNum.Text
End Sub
End Class
I use it in my page like this:
Put this on page definition:
xmlns:local="clr-namespace:Demo"
And put this in the content section:
<local:NumericUpDown Numeric="{Binding Path=score, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}"/>
Of course I have already set DataContext on the container and all other databound controls work as they should. But the textbox in my custom control turned out empty! It doesn't end here. When I type something in the textbox and when I give it some value using decrease and increase button, the value is transferred to my DataTable; which means this usercontrol does work to some extend. Where did I do wrong? Why won't the Textbox content be initialized with the starting value?
After a little more testing. It seems that my usercontrol doesn't work in 'Two-Way'. It doesn't receive data from DataTable, it only propagates value to it. How do I fix it?
The issue is that you are not binding the Text property of txtNum to your Numeric property.
<TextBox x:Name="txtNum" Grid.Column="0" x:FieldModifier="private"
Text="{Binding Path=Numeric, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"/>
Then you can remove txtNum_TextChanged, and modify your up/down click handlers to just update the Numeric property, e.g.:
Private Sub cmdUp_Click(sender As Object, e As RoutedEventArgs)
If Me.Numeric < Me.Maximum Then
Me.Numeric += 1
Else
Me.Numeric = Me.Maximum
End If
End Sub
Private Sub cmdDown_Click(sender As Object, e As RoutedEventArgs)
If Me.Numeric > Me.Minimum Then
Me.Numeric -= 1
Else
Me.Numeric = Me.Minimum
End If
End Sub
Note that there are still lots of issues - a user can enter a value outside of the allowed range, or non-numeric data (which will break things!), etc. For this specific problem, you could check out the Extended EPF Toolkit, which has various up/down controls.
I have a CustomerOrder class which has 2 properties namely CustomerName and NumberOfOrders. I have a Usercontrol to show these two properties, namely ucCustomerOrder.
Following the code corresponding
Customer Class
Public Class CustomerOrder
Private m_CustomerName As String = String.Empty
Private m_NumberOfOrders As Decimal = 0
Public Property CustomerName As String
Get
Return m_CustomerName
End Get
Set(ByVal value As String)
m_CustomerName = value
End Set
End Property
Public Property NumberOfOrders As Decimal
Get
Return m_NumberOfOrders
End Get
Set(ByVal value As Decimal)
m_NumberOfOrders = value
End Set
End Property
End Class
UserControl XAML
<UserControl x:Class="ucCustomerOrder"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="99" d:DesignWidth="300">
<Grid>
<Label Name="lblCustomerName" Content="{Binding Path=CustomerName}" Height="28" HorizontalAlignment="Left" Margin="23,12,0,0" VerticalAlignment="Top" Width="237" />
<Label Name="lblNoOfOrders" Content="{Binding Path=NumberOfOrders}" Height="28" HorizontalAlignment="Left" Margin="23,46,0,0" VerticalAlignment="Top" Width="237" />
</Grid>
</UserControl>
Code behind the User control is as follows.
Public Class ucCustomerOrder
Private m_CustomerOrder As CustomerOrder
Public Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
m_CustomerOrder = New CustomerOrder
Me.DataContext = m_CustomerOrder
End Sub
Public Property CustomerOrder As CustomerOrder
Get
Return m_CustomerOrder
End Get
Set(ByVal value As CustomerOrder)
m_CustomerOrder = value
Me.DataContext = m_CustomerOrder
End Set
End Property
End Class
In my main window I have a combo box control and ucCustomerOrder (User Control) and also I have list of Customer’s orders in Dictionary object. Like as follows
XAML For main windows looks like
<Window x:Class="DictionaryTest"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="DictionaryTest" Height="182" Width="300" xmlns:my="clr-namespace:TestUserControls">
<Grid>
<ComboBox Height="23" Width="254" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="12,12,0,0" Name="cboCustomerOrders" ItemsSource="{Binding}" DisplayMemberPath="Key" SelectedValuePath="Value"/>
<my:ucCustomerOrder HorizontalAlignment="Left" VerticalAlignment="Top" Margin="12,56,0,0" x:Name="UcCustomerOrder1"/>
</Grid>
</Window>
Code Behind for my main window as follows.
Public Class DictionaryTest
Private Function GetCustomers() As Dictionary(Of String, CustomerOrder)
Dim customerList As New Dictionary(Of String, CustomerOrder)
Dim customer1 As New CustomerOrder
With customer1
.CustomerName = "XXXX"
.NumberOfOrders = 100
End With
Dim customer2 As New CustomerOrder
With customer2
.CustomerName = "ZZZZ"
.NumberOfOrders = 150
End With
customerList.Add("X-Customer", customer1)
customerList.Add("Z-Customer", customer2)
Return customerList
End Function
Private Sub DictionaryTest_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
Try
cboCustomerOrders.ItemsSource = GetCustomers()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
How can I set my selected CustomerOrder object to the user control using Binding?
Doing projects for fun helps me learn. Here is a project that I am working on and I have already learned so much. I would like to see the program be less CPU intensive though. Does anyone have any suggestions on how I could do that?
Basically this program just overlays some snow flakes onto a computer screen.
EDIT:
What I am currently taking a look into is to see if I can use DoubleAnimationUsingPath and bind to the PathGeometry. While I am trying to figure this out I welcome any suggestion or tips regarding this method or any other.
WPF/XAML:
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
AllowsTransparency="True"
WindowStyle="None"
Title="MainWindow" Height="350" Width="525" Background="Transparent" Topmost="True" WindowState="Maximized" ResizeMode="NoResize">
<Canvas Name="canvas1">
</Canvas>
</Window>
VB.NET Main Window:
Imports System.ComponentModel
Class MainWindow
Dim bw As New BackgroundWorker
Dim flakes(17) As flake
Private Sub Window_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
For i = 0 To flakes.Count - 1
flakes(i) = New flake
flakes(i).image.DataContext = flakes(i)
flakes(i).image.SetBinding(Canvas.LeftProperty, "left")
flakes(i).image.SetBinding(Canvas.TopProperty, "top")
canvas1.Children.Add(flakes(i).image)
Next
AddHandler bw.DoWork, AddressOf backgroundMover
bw.RunWorkerAsync()
End Sub
Private Sub backgroundMover()
While (True)
For Each f In flakes
f.move()
Next
System.Threading.Thread.Sleep(50)
End While
End Sub
End Class
VB.Net flake class:
Imports System.ComponentModel
Public Class flake
Implements INotifyPropertyChanged
Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged
Private Sub NotifyPropertyChanged(ByVal info As String)
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(info))
End Sub
Private Property startLeft As Double
Private Property _left As Double
Private Property _top As Double
Private Property speed As Double
Private Property amplitude As Double
Private Property period As Double
Public Property image As New Image
Private Shared Property r As New Random
Public Sub New()
_image.Width = 28
_image.Height = 26
_image.Source = New System.Windows.Media.Imaging.BitmapImage(New Uri("/snowTest;component/Images/blue-pin-md.png", UriKind.Relative))
startFresh()
End Sub
Public ReadOnly Property left As Double
Get
Return _left
End Get
End Property
Public ReadOnly Property top As Double
Get
Return _top
End Get
End Property
Public Sub startFresh()
_top = -30
amplitude = r.Next(5, 35)
period = 1 / r.Next(20, 60)
speed = r.Next(15, 25) / 10
startLeft = r.Next(0, System.Windows.SystemParameters.PrimaryScreenWidth)
End Sub
Public Sub move()
If _top > System.Windows.SystemParameters.PrimaryScreenHeight Then
startFresh()
Else
_top += speed
_left = amplitude * Math.Cos(period * _top) + startLeft
End If
NotifyPropertyChanged("top")
NotifyPropertyChanged("left")
End Sub
End Class
Updating LeftProperty and TopProperty on your UIElement inside the canvas forces a new layout pass for each update. Layout in WPF is pretty expensive from a performances point of view. You should use UIElement.RenderTransform Property instead.