|
If you need info from the user that is required and is simple, then yes, I think it is OK to open it from the code behind. Remember, the separation of concerns in MVVM is to support testing of the VMs and the models independent of the view. So if you need to pop an input box or a file dialog or something from the control's code-behind, then go ahead if that is what makes the most sense.
That being said... although I think it is OK to do if that is what it takes to solve the problem, I think you are taking out some technical debt if you do it this way. You may want to reconsider your whole approach a bit. Normally, you would want the view model to react to a change in state in the view. With a control in the view you would normally want it to react to a change in the properties on the VM it is bound to. So generally, you would enter a state whereby a new employee needs picked, the VM might open a window to get the selection from the user. Then you would validate that result (in the VM) and set the property on the VM that your control is bound to so it can display the information. Generally we try to keep the brains out of the controls because that complicates things and makes it harder to maintain. The control should basically be able to take some information and display it. Any logic more than that should generally be in the VM.
And as one last thought... does your control need to know anything about the backend data other than being bound to a collection of the available options? Meaning, is there any logic in the control to manipulate the backing data such that there is a dependency on the backing data? Or, in other words, do you have strongly-typed references to data objects in your code behind? If so, that is definitely wrong. (References to members as part of the data template in code or in xaml don't count)
HTH.
|
|
|
|
|
I want to set a RadProgess Bar With Timer on Methodload Plaese Suggest me to get a right answer
With Regards
Ram
|
|
|
|
|
As a start I would investigate the Telerik examples[^], they tend to supply a comprehensive set. If you don't get and indication of how to do the work then search for WPF/Silverlight progress bar in Code Project or Google.
I would create a timer and an integer property with onpropertychange, each time the timer ticks I would update the int property.
I would then bind the progress bar's progress value to the int property. I would also bind the visibility value to a boolean property set when I begin and end the timer.
Never underestimate the power of human stupidity
RAH
|
|
|
|
|
Hello,
In WPF, I open window2 from window1 with a button click keeping window1 open. When I close window2, I want to display 2 values in window1. How can this be achieved?
Thanks
|
|
|
|
|
Assuming the values you want to show are contained in Window2.
You need to register a method to the "Closed" event of Window2.
Like this;
private void StartWindow()
{
Window window2 = new Window();
window2.Closed += new EventHandler(window2_Closed);
window2.Show();
}
void window2_Closed(object sender, EventArgs e)
{
Window window2 = sender as Window;
if (window2 != null)
{
MessageBox.Show(window2.Text1);
MessageBox.Show(window2.Text2);
}
}
|
|
|
|
|
Try it with DataBinding. Just bind the Controls in Window1 and Window2 on the properties of the same object.
class Data : INotifyPropertyChanged
{
private int myVar;
public int MyProperty
{
get { return myVar; }
set
{ myVar = value;
this.OnPropertyChanged("MyProperty");
}
}
#region PropertyChangedEvent
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}
And e.g.
Data d = new Data();
Window1.DataContext = d;
Window2.DataContext = d;
In Windows2.xaml
<TextBox Text={Binding MyProperty} />
e.g. In Windows1.xaml
<pre lang="HTML">
<Label Content={Binding MyProperty} />
</pre>
|
|
|
|
|
hi all,
I used the Cell Template in listview ,
but i don't know how to gain access to the controls.
XAML code:
<ListView FontSize="13" Margin="1,2,3,0" Name="lsvCheck" Template="{DynamicResource ListViewControlTemplate1}" Height="139" VerticalAlignment="Top">
<ListView.View>
<GridView>
<GridViewColumn DisplayMemberBinding="{Binding Row}" Header="Row" Width=" 30" />
<GridViewColumn DisplayMemberBinding="{Binding fldCheckNum}" Header="Number" Width=" 150" />
<GridViewColumn Header="RevivalDate" Width="160" x:Name="Coldate">
<GridViewColumn.CellTemplate>
<DataTemplate>
<DatePicker Visibility="Hidden" Name="datePicker1" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Passed" Width="100" x:Name="chk" >
<GridViewColumn.CellTemplate >
<DataTemplate>
<CheckBox Name="chkPassed" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="NotPassed" Width="100" x:Name="chk1">
<GridViewColumn.CellTemplate>
<DataTemplate>
<CheckBox Name="chkNotPassed" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
For example:
I'm going to be checking "chkNotPassed" control,"datePicker1" control to be seen.(visibility.visit)
Note:
Code Behind (C#):lsvCheck.ItemsSource = tblCheck.DefaultView;
Thank you for any help you..
|
|
|
|
|
I think you have the wrong idea about xaml, you should not be monitoring the state of the controls but the state of the data bound to those controls.
Your listview binds to a collection
The controls in your template should bind to field/element in that collection
when the value of a field chanes then you should set a property that manages the visibility of datepicker.
Never underestimate the power of human stupidity
RAH
|
|
|
|
|
 Thank you for reply.
According to you I've applied the following changes:
<ListView FontSize="13" Margin="1,2,3,0" Name="lsvCheck" Template="{DynamicResource ListViewControlTemplate1}" Height="139" VerticalAlignment="Top">
<ListView.View>
<GridView>
<GridViewColumn DisplayMemberBinding="{Binding Row}" Header="Row" Width=" 30" />
<GridViewColumn DisplayMemberBinding="{Binding fldCheckNum}" Header="Number" Width=" 150" />
<GridViewColumn Header="Passed" Width="100" x:Name="chk" >
<GridViewColumn.CellTemplate >
<DataTemplate>
<CheckBox Name="chkPassed" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="NotPassed" Width="100" x:Name="chk1">
<GridViewColumn.CellTemplate>
<DataTemplate>
<CheckBox Name="chkNotPassed" IsChecked="{Binding fldIsPass}" Checked="FindElement" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="RevivalDate" Width="160" x:Name="Coldate">
<GridViewColumn.CellTemplate>
<DataTemplate>
<DatePicker Visibility="Hidden" SelectedDate ="{Binding fldRevivalDate}" Name="datePicker1" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
and Method FindElement:
private void FindElement(object sender, RoutedEventArgs e)
{
try
{
ListViewItem row= lsvCheck.ItemContainerGenerator.ContainerFromIndex(lsvCheck.SelectedIndex) as ListViewItem;
DatePicker date = null;
if (row != null)
{
ContentPresenter templateParent = GetFrameworkElementByName<ContentPresenter>(row);
DataTemplate dataTemplate = Coldate.CellTemplate;
if (dataTemplate != null && templateParent != null)
{
row.ApplyTemplate();
date = dataTemplate.FindName("datePicker1", templateParent) as DatePicker;
if (date != null)
{
date.Visibility = Visibility.Visible;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
private static T GetFrameworkElementByName<T>(FrameworkElement referenceElement) where T : FrameworkElement
{
FrameworkElement child = null;
for (Int32 i = 0; i < VisualTreeHelper.GetChildrenCount(referenceElement); i++)
{
child = VisualTreeHelper.GetChild(referenceElement, i) as FrameworkElement;
System.Diagnostics.Debug.WriteLine(child);
if (child != null && child.GetType() == typeof(T))
{ break; }
else if (child != null)
{
child = GetFrameworkElementByName<T>(child);
if (child != null && child.GetType() == typeof(T))
{
break;
}
}
}
return child as T;
}
However, this error is:
"This operation is valid only on elements that have this template applied"
I do not know how to fix the error. In your opinion, where is the problem? And what do you suggest a way
Thanks for the idea!
|
|
|
|
|
you can create a visibility converter using chkNotPassed as value and apply it on datePicker1.
don't worry and don't get frustrated. everything will eventually sort out and then we will regret being frustrated. the only thing that matters is conscious efforts to make things right. - Rahul Rajat Singh
Just that something can be done, doesn't mean it should be done. Respect developers and their efforts! - Jyothikarthik_N
|
|
|
|
|
Excuse me.I do not understand what you mean.
Can you tell me more??
|
|
|
|
|
Follow this example:
Visibility Converter (Value Converter) [^]
don't worry and don't get frustrated. everything will eventually sort out and then we will regret being frustrated. the only thing that matters is conscious efforts to make things right. - Rahul Rajat Singh
Just that something can be done, doesn't mean it should be done. Respect developers and their efforts! - Jyothikarthik_N
|
|
|
|
|
Hi, please help me regards this issue.
When I click on child module name should be send to the viewmodel as parameter.
<TreeView ItemsSource="{Binding ModuleCategories}" Canvas.Left="16" Canvas.Top="15" Height="350" Name="treeView1" Width="150" >
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectedItemChanged">
<i:InvokeCommandAction Command="{Binding TreeViewCommand}"
CommandParameter="{Binding ElementName=treeView1, Path=SelectedItem}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Children}" >
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}" />
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
|
|
|
|
|
now I'm work on the silverlight for a project of windows embedded compact7, and I want to construct two windows(of course one exe/process)
for my project. because this project is a car audio product, a screen is nearby the driver and the other is on the back of the first chair for the people sit at the back.
now how to construct the other windows, could you give me some ideas?
|
|
|
|
|
Hire a developer!
Never underestimate the power of human stupidity
RAH
|
|
|
|
|
|
Hi,
I'm working at a custom control in WPF. This control should work as menu with buttons. The buttons are on left side of the window (4..5 one below the other) and realized by rectangles.
At the first time I used triggers with setters to set the colors of the rectangle
( Button Enabled = DarkBlue,
Button Disabled = LightBlue,
MouseOver = MiddleBlue).
This worked fine for every button. If the mouse was over the enabled buttons, the button color became middleblue and by leaving the button, the button became darkblue. The disabled button was always lightblue. If I switched the buttons from enable to disable, the previous button became dark blue and the IsMouseOver works again.
But now, I decided to animate the rectangles by color transition. Now I'm using the MultiTrigger to animate the color transition. But it doesn't work. When starting the application the button at the top is disabled. If I click the next button under the button at the top, the clicked button becomes disable (lightblue) and the top button becomes enabled (darkblue). Now the IsMouseOver property doesn't work for the first button in the top. But it works already for the buttons I never clicked.
I think, that the disabled button, which becomes enable again, ignores the MouseOver property. How can I solve this problem?
Here is the code:
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="IsEnabled" Value="True" />
<Condition Property="IsMouseOver" Value="True" />
</MultiTrigger.Conditions>
<MultiTrigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<ColorAnimation Storyboard.TargetName="rightRectangle"
Storyboard.TargetProperty="(Rectangle.Fill).Color"
To="{StaticResource colorMiddleBlue}"
Duration="0:0:0.25" />
</Storyboard>
</BeginStoryboard>
</MultiTrigger.EnterActions>
<MultiTrigger.ExitActions>
<BeginStoryboard>
<Storyboard>
<ColorAnimation Storyboard.TargetName="rightRectangle"
Storyboard.TargetProperty="(Rectangle.Fill).Color"
To="{StaticResource colorDarkBlue}"
Duration="0:0:0.20" />
</Storyboard>
</BeginStoryboard>
</MultiTrigger.ExitActions>
</MultiTrigger>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="IsEnabled" Value="False"/>
</MultiTrigger.Conditions>
<MultiTrigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<ColorAnimation Storyboard.TargetName="rightRectangle"
Storyboard.TargetProperty="(Rectangle.Fill).Color"
Duration="0:0:0.15"
To="{StaticResource colorLightBlue}" />
</Storyboard>
</BeginStoryboard>
</MultiTrigger.EnterActions>
<MultiTrigger.ExitActions>
<BeginStoryboard>
<Storyboard>
<ColorAnimation Storyboard.TargetName="rightRectangle"
Storyboard.TargetProperty="(Rectangle.Fill).Color"
Duration="0:0:0.15"
To="{StaticResource colorDarkBlue}" />
</Storyboard>
</BeginStoryboard>
</MultiTrigger.ExitActions>
</MultiTrigger>
|
|
|
|
|
I am trying to use scroll bar on canvas but scroller is not coming, only control is visible, i am unable to scroll up and down. Please help me.
<ScrollViewer VerticalScrollBarVisibility="Visible" HorizontalScrollBarVisibility="Visible">
<Canvas Visibility="{Binding EnableEdit, Converter={StaticResource BoolToVis}}" Background="AliceBlue" Canvas.Left="208" Canvas.Top="174" Height="254" Name="canvasEdit" Width="424">
<ItemsControl x:Name="itemsControl" Canvas.Left="{Binding SetPosition}" ItemsSource="{Binding Test}">
</ItemsControl>
</canvas>
</ScrollViewer>
modified 18-Nov-13 8:08am.
|
|
|
|
|
Hi,
you use the scroll bar on the item above. If it's a grid, the grid contains the scroll bar.
Note, the canvas height and width must exceed the window parameter. Otherwise the scroller of the scroll bar is inactive.
The scroller is only visible when the content is larger than the item that you want to display.
For example:
<Window x:Class="TestWindow.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>
<ScrollViewer VerticalScrollBarVisibility="Visible"
HorizontalScrollBarVisibility="Visible">
<Canvas Visibility="{Binding EnableEdit, Converter={StaticResource BoolToVis}}"
Background="AliceBlue"
Canvas.Left="208"
Canvas.Top="174"
Height="500" <!-- this value must be greater than the window height -->
Width="700"
Name="canvasEdit" >
<ItemsControl x:Name="itemsControl"
Canvas.Left="{Binding SetPosition}"
ItemsSource="{Binding Test}"/>
</Canvas>
</ScrollViewer>
</Grid>
</Window>
|
|
|
|
|
Thanks... 
|
|
|
|
|
|
I have to canvas one over another and I am creating a rectangle on Child canvas in which i want to display the parent canvas background. i am able to do it using Opacity mask but when I try to add border to rectangle for that area also it displays Canvas bakground
<Canvas Width="772" Name="Canvas2" Height="464" >
<Canvas.OpacityMask>
<VisualBrush Stretch="Fill" Viewbox="0,0,800,600" ViewboxUnits="Absolute" Viewport="0,0,800,600" ViewportUnits="Absolute">
<VisualBrush.Visual>
<Canvas Width="800" Height="600" Background="#1000" >
<Button x:Name="VisualButton1" Width="200" Height="100" BorderBrush="#0000" BorderThickness="100" />
</Canvas>
</VisualBrush.Visual>
</VisualBrush>
</Canvas.OpacityMask>
<Canvas.Background>
<ImageBrush ImageSource="C:\Users\Public\Pictures\Sample Pictures\Desert.jpg" />
</Canvas.Background>
</Canvas>
|
|
|
|
|
|
I have 2 pages (User and UserListing) When I Add new user on User Page then change page to UserListing Page the ComboBoxUser on UserListing Page wont update automatically. Any Idea to solve this ?
this is my code User.cs
public class User : INotifyPropertyChanged
{
string _firstName;
public string FirstName {
get { return _firstName; }
set {
_firstName = value;
OnPropertyChanged("FirstName");
OnPropertyChanged("FullName");
}
}
string _lastName;
public string LastName {
get { return _lastName; }
set {
_lastName = value;
OnPropertyChanged("LastName");
OnPropertyChanged("FullName");
}
}
public string FullName
{
get { return string.Format("{0} {1}", FirstName, LastName); }
}
int _gender;
public int Gender {
get { return _gender; }
set {
_gender = value;
OnPropertyChanged("Gender");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
UserListingViewModel.cs
public class UserListingViewModel : INotifyPropertyChanged
{
public UserListingViewModel()
{
LoadDataUser();
}
public void LoadDataUser()
{
ComboUserData = new ObservableCollection<User>();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings[
"dLondre.Properties.Settings.CSLONDRE"].ConnectionString);
string str = "";
str += "SELECT userid,firstname + ' ' + lastname as name FROM [user] ";
SqlCommand com = con.CreateCommand();
com.CommandText = str;
try
{
con.Open();
SqlDataReader sdr = com.ExecuteReader();
while (sdr.Read())
{
ComboUserData.Add(new User { UserID = (string)sdr["userid"], FirstName = (string)sdr["name"]});
}
com.Dispose();
con.Close();
con.Dispose();
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
ObservableCollection<User> _comboUserData;
public ObservableCollection<User> ComboUserData
{
get
{
if (_comboUserData == null)
_comboUserData = new ObservableCollection<User>();
return _comboUserData;
}
set
{
if (value != _comboUserData)
_comboUserData = value;
OnPropertyChanged("ComboUserData");
}
}
User _user;
public User SelectedUserID
{
get { return _user; }
set
{
_user = value;
OnPropertyChanged("SelectedUserID");
}
}
}
XAML
<ComboBox x:Name="DDUserId"
Width="140"
DisplayMemberPath="FirstName"
IsSynchronizedWithCurrentItem="True"
ItemsSource="{Binding ComboUserData,Mode=TwoWay}"
SelectedItem="{Binding SelectedUserID}">
</ComboBox>
|
|
|
|
|
Hi
Could you please tell whether the ViewModel is set as the DataContext of the View containing ComboBox
like the below.
<Page.DataContext>
</Page.DataContext>
Karthikeyan
|
|
|
|