我尝试使用单击事件的命令绑定按下按钮来更改画布的颜色,以避免MyView.xaml.cs文件中的任何代码。该命令正在激活,并且消息框在更改之前和之后显示正确的颜色代码值,因此设置了新颜色但画布的颜色不会更改。如果使用单击事件和MyView.xaml.cs中的代码后面的所有工作正常但我想在MyView.xaml.cs文件中使用命令绑定并且没有代码。我怎么能这样做,我做得不对的是什么?
MainWindow.xaml
public class Jdbcdemo {
public static void main(String[] args) {
try
{
//loading the jdbc driver
Class.forName("com.mysql.jdbc.Driver").newInstance();
//get a connection to database
Connection myConn=DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbctry","your username","your password");
//create a statement
Statement stmt=myConn.createStatement();
//execute sql query
ResultSet rs=stmt.executeQuery("select * from employee");
//process the result
while(rs.next())
{
System.out.println(rs.getString("name")+" = "+rs.getString(1));
}
}
catch(SQLException e)
{
System.out.println(e);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
MyView.xaml文件
<Window x:Class="WpfApp1.MainWindow"
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"
xmlns:View="clr-namespace:WpfApp1.View"
xmlns:ViewModel="clr-namespace:WpfApp1.ViewModel"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525" Background="YellowGreen"
WindowStartupLocation="CenterScreen">
<Window.DataContext>
<ViewModel:MyClass/>
</Window.DataContext>
<View:MyView/>
</Window>
MyClass.cs
<UserControl x:Class="WpfApp1.View.MyView"
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"
xmlns:ViewModel="clr-namespace:WpfApp1.ViewModel"
xmlns:View="clr-namespace:WpfApp1.View">
<Canvas Name="MainCanvas" Height="300" Width="502" Background="#FF148B63">
<Button Name="ChangeColorButton" Command="{Binding CommandChangeColor}" Content="new color" Height="25" Width="55" Margin="225,268,225,10"/>
</Canvas>
</UserControl>
答案 0 :(得分:0)
由于您可以拥有许多UserControl实例,MyClass如何知道它应该更新哪个MainCanvas实例? 与CommandChangeColor的绑定类似,您还应该将Background绑定到MyClass中的某些属性。类似的东西:
的Xaml:
<Canvas Name="MainCanvas" Height="300" Width="502" Background="{Binding BackGroundColor}">
<Button Name="ChangeColorButton" Command="{Binding CommandChangeColor}" Content="new color" Height="25" Width="55" Margin="225,268,225,10"/>
</Canvas>
MyClass.cs
public SolidColorBrush BackGroundColor {get;set;}
public void ChangeColor()
{
MessageBox.Show("Color before: " + MainCanvas.Background.ToString());
Random rnd = new Random();
int i = rnd.Next(_listOfColors.Count - 1);
BackGroundColor = new SolidColorBrush(_listOfColors[i]);
MessageBox.Show("Color after: " + MainCanvas.Background.ToString());
}
您可能还想实现INotifyPropertyChanged。