This one is driving me crazy:-)
Lets say I have some test xaml code:
<Window x:Class="ProWPFInCSharpyTestProject.ValidationTest"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="ValidationTest" Height="300" Width="300">
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<TextBox Margin="10" Name="someTextBox" VerticalAlignment="Top" Text="" />
<TextBox Grid.Row="1" Margin="10" Name="SomeTextBox2" VerticalAlignment="Top" />
<TextBlock Grid.Row="2" Margin="10" Name="errorMessageTextBlock" />
<Button Content="Click Me" Grid.Row="3" Margin="10" VerticalAlignment="Top" />
</Grid>
</Window>
Now, I have no object bound to it, because it will collect data from the form and throw it in the database. But now I want to validate if the fields are empty when the button is clicked and show an err开发者_C百科or message. Almost every single tutorial I have looked at has an object bound to the grid but this is not relevant to me.
Why can't this be more like asp.net? Just put a validator with a validator group. It would things so much less cryptic and complex than it is now.
Sorry man, but you're doing WPF not ASP.NET. I understand that WPF can be frustrating but is not a good idea to bend a technology to your old habits. Having said that, You're talking about gathering the data entered then pass it to the database. One way to do it in WPF is using a ViewModel or any object to act as some kind of container. The WPF binding stuff will tell you if something went wrong. Then you can pass/translate your objects to the Data Layer/ORM and then lastly hit the database.
Maybe Kent approach works, but not in complex scenarios.
OK, assuming you really don't want a model:
<TextBox Margin="10" Name="someTextBox" VerticalAlignment="Top" Text="" />
<TextBox Grid.Row="1" Margin="10" Name="SomeTextBox2" VerticalAlignment="Top" />
<TextBlock Grid.Row="2" Margin="10" Name="errorMessageTextBlock" />
<Button Name="button" Content="Click Me" Grid.Row="3" Margin="10" VerticalAlignment="Top" />
Then in the code behind:
button.Click += delegate
{
if (someTextBox.Text == "" && someTextBox2.Text == "")
{
MessageBox.Show("Error!");
}
else
{
DoSomethingCool();
}
};
As a hacky way to use the validation infrastructure without defining your own model, you could do this:
<TextBox>
<TextBox.Text>
<Binding Path="Tag" RelativeSource="{RelativeSource Self}">
<Binding.ValidationRules>
<!-- whatever rules you want here -->
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
This hijacks the TextBox.Tag
property as a place to store the bound data, which enables you to use Binding.ValidationRules
.
But you're really resisting one of WPF's strongest attractions by not using data binding.
The clean way to do this is to define a model, bind the view to that model, and implement IDataErrorInfo
in your model if you want validation.
精彩评论